2017-04-15 9 views
1

私は角度4とfirebaseを学んでいます。ここでは、私はコースのリストのためのドロップダウンセレクターを構築しようとしている。角度2火災ベースドロップダウンセレクター

コースを選択すると、コースの説明が別の部門に表示されます。

courses.component.html

<select class="form-control" 
 
\t  [ngModel]="(selectedCourse$ | async)" 
 
\t \t (ngModelChange)="onChange($event)" 
 
> 
 
<option *ngFor="let course of (courses$ | async)" 
 
\t  [ngValue]="course" 
 
> 
 
    {{ course.description }} 
 
</option> 
 
</select> 
 
\t \t  
 
<div *ngIf="(selectedCourse$ | async)"> 
 
    {{ course.description }} 
 
</div>

courses.component.ts

import { Component, OnInit } from '@angular/core'; 
 
import { Observable } from 'rxjs/Rx'; 
 

 
import { Course } from '../shared/model/course'; 
 
import { CoursesService } from '../shared/model/courses.service'; 
 

 
@Component({ 
 
    selector: 'app-courses', 
 
    templateUrl: './courses.component.html', 
 
    styleUrls: ['./courses.component.css'] 
 
}) 
 
export class CoursesComponent implements OnInit { 
 

 
    courses$: Observable<Course[]>; 
 
    selectedCourse$: Observable<Course>; 
 
    courseUrl: string; 
 

 
    constructor( 
 
     private coursesService: CoursesService 
 
    ) { } 
 

 
    ngOnInit() { 
 
     this.courses$ = this.coursesService.findAllCourses(); 
 

 
     this.selectedCourse$ = this.coursesService.findCourseByUrl(this.courseUrl); 
 
    } 
 

 
    onSelect(course: Course): void { 
 
     console.log(course); 
 
     this.selectedCourse$ = course; 
 
    } 
 

 
    onChange(newValue) { 
 
     console.log(newValue); 
 
     this.selectedCourse$ = newValue; 
 
    } 
 

 
}

私はコースを選択することができますが、コースの説明がで表示されません下のdiv。どんな助けでも大歓迎です。

答えて

0

あなたが選択するとObservableではなく普通のJSオブジェクトになります。選択した値を割り当てるために使用しているnewValueはオブジェクトなので、selectedCourseはオブジェクトです。

また、あなたの条件divでしようとしたように、選択の外からcourseにアクセスすることはできません。だから、そこにすべてのあなたの条件付きのdivに{{ selectedCourse$.description }}代わりの{{ course.description }}すべてを表示する必要があります(私はドル記号を削除した)このよう

<div *ngIf="selectedCourse"> 
    {{ selectedCourse.description }} 
</div> 

になりますし、あなたのngModelもその後、ちょうど次のようになります。

[ngModel]="selectedCourse" 

Demo

+0

これは機能します。ありがとうございました。 –

+0

あなたは大歓迎です!あなたの問題を解決したので、この回答の投票の下にある灰色のチェックマークをクリックして回答を受け入れることを検討してください;)さらに、幸せなコーディング! :) – Alex

+1

素晴らしい!私はここで新しいです。ダニのあなたの親切な思い出しのためにありがとう。 –