Display data json in dropdown using angular material

Issue

I have created an Angular project with angular material and I want to display a list of units inside a dropdown.

the data comes like expected like this :

enter image description here

this is my .ts code :

ListUnits:Array<Unit>=[]

units(){
return this.trq.getListUnit().subscribe(
  (data)=>{
    this.ListUnits.push(data.respModel);
    console.log(this.ListUnits);
  }
)

}

and here is my .HTML code :

<mat-label>Unite</mat-label>
            <mat-select formControlName= "unite_id" required>
                <mat-option *ngFor="let unit of ListUnits"[value]="unit.id">
                  {{unit.unitName}}
                </mat-option>
            </mat-select>

but unfortunately, nothing appears
Which are the steps to follow to achieve that?

Solution

You are pushing array inside array. Instead do this if you want to retain current data in ListUnits

this.ListUnits = [...this.ListUnits, ...data.respModel];

Otherwise simply assign array from response to ListUnits

this.ListUnits = data.respModel;

Answered By – zainhassan

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.