Reputation: 487
I have a database table airline
and I want to show all data from the table in a drop down list
and then to be able to choose one item from the list.
airline.ts
export class Airline {
airline_id: number;
name: string;
symbol: string;
}
My HTML code, that doesn't work (only shows drop down list without data inside):
<mat-form-field>
<mat-select placeholder="Airlines" [(ngModel)]="selectedValue" name="airline">
<mat-option *ngFor="let airline of airlines" [value]="airline.name">
{{airline.symbol}}
</mat-option>
</mat-select>
</mat-form-field>
Actually it looks like this (without data inside the list):
airlineService.ts
export class AirlineService {
private baseUrl = 'http://localhost:8080/api/airlines';
constructor(private http: HttpClient) {
}
getAirline(airline_id: number): Observable<Airline> {
return this.http.get<Airline>(`${this.baseUrl}/${airline_id}`);
}
getAirlinesList(): Observable<any> {
return this.http.get(`${this.baseUrl}`);
}
}
airlines-list.component.ts
export class AirlinesListComponent implements OnInit {
airlines: Observable<Airline[]>;
airline_id: number;
selectedValue: string;
@Input() airline: Airline;
constructor(private airlineService: AirlineService) { }
ngOnInit() {
this.reloadData();
}
reloadData() {
this.airlines = this.airlineService.getAirlinesList();
}
}
Upvotes: 3
Views: 1674
Reputation: 25151
Since you declared the airlines
variable as an Observable, you need to treat is as such when referring to it in the template.
Change your ngFor
from this:
*ngFor="let airline of airlines"
to this:
*ngFor="let airline of (airlines | async)"
Upvotes: 5