Kenneth
Kenneth

Reputation: 43

angular 2 firebase dropdown selector

I am learning Angular 4 and firebase. Here, i'm trying to build a dropdown selector for a list of courses.

After selecting a course, the course description should appear in another div below.

courses.component.html

<select class="form-control" 
	    [ngModel]="(selectedCourse$ | async)" 
		(ngModelChange)="onChange($event)"
>
<option *ngFor="let course of (courses$ | async)" 
	    [ngValue]="course"
>
    {{ course.description }}
</option>
</select>
		    
<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;
    }

}

I can select the course, but the course description will not show up in the div below. Any help will be much appreciated.

Upvotes: 1

Views: 632

Answers (1)

AVJT82
AVJT82

Reputation: 73357

When you make your select, it is no longer an Observable, but a plain JS object. The newValue you are using to assign the chosen value is an object, so selectedCourse is therefore an object.

Also, you cannot access course from outside the select, like you have tried to do in your conditional div. So there you should display {{ selectedCourse$.description }} instead of {{ course.description }} All in all your conditional div should look like this (I've removed the dollar sign)

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

and your ngModel should also then be just:

[ngModel]="selectedCourse"

Demo

Upvotes: 1

Related Questions