Search code examples
angulartypescriptangular-materialmd-select

How to populate mat-option with elements from an array received from api


I have an issue and i think im missing something because i cant populate the md-option with the elements received from an API.

Here is the service.ts where i make the call and i try to retrieve the data from the API.

getCars(){
 this.http.get(this.rootURL+'/car/getallcars')
 .toPromise()
 .then(res => this.carList = res as Cars[]);
}

Basically the api returns something like this:

{
"id": "b49981fc-730e-49fc-b5e4-0159f4b42c9d",
"brand": "Mercedes",
"model": "G-Klasse",
"mileage": 19000,
"isAvailable": true
}

In the html i have like this:

<mat-form-field appearance="fill">
<mat-label>Field</mat-label>
<mat-select name="myField"  #brand="ngModel [(ngModel)]="service.formData.brand">
<mat-option *ngFor ="let car of carList" [value]="car.id" >{{car.brand}}</mat-option>
</mat-select>

Here comes the issue.. I dont know how should i write in the component.ts to take the elements from API and populate this mat-option.


Solution

  • Can you please try with below code?

    in your service.ts file replace below code

    getCars(){
      return this.http.get(this.rootURL+'/car/getallcars');
    }
    

    In your component.ts file

    ngOnInit() {
        if (!this.service.formData) {
            this.resetForm();
        }
        this.getCarsData();
    }
    
    cars: any = [];
    getCarsData(): void{
        this.service.getCars().subscribe(data => {
           console.log(data);
           this.cars = data;
        });
    }
    

    In your component.html file

    <mat-label>Field</mat-label>
    <mat-select name="myField"  #brand="ngModel [(ngModel)]="service.formData.brand">
      <mat-option *ngFor ="let car of cars" [value]="car.id" >{{car.brand}}</mat-option>
    </mat-select>