Home > Mobile >  ngFor netsted array with objects in mat select option
ngFor netsted array with objects in mat select option

Time:10-19

I have mat form field with option select

        <mat-form-field appearance="outline">
          <mat-label>TestMat</mat-label>
          <mat-select placeholder="TestMat"  [formControl]="testControl">  
                <mat-option *ngFor="let arr of arrTmp" [value]="arr">
               {{arr.name}}
            </mat-option>           
            </mat-select>   
        </mat-form-field>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

where arrTmp =

[
    [{
        "name": "name1",
        "id": "1"
    }],

    [{
        "name": "name2",
        "id": "2"
    }, {
        "name": "name3",
        "id": "2"
    }]

]

as a result inside of mat form field i have

[object Object]
[object Object],[object Object] 

how i can display arr.name normally?

CodePudding user response:

You need to use one extra for loop for nested array, please see the below code

    <mat-form-field appearance="outline">
          <mat-label>TestMat</mat-label>
          <mat-select placeholder="TestMat"  [formControl]="testControl">
               <ng-container *ngFor="let arr of arrTmp">
                <mat-option *ngFor="let item of arr" [value]="item">
                {{item.name}}
              </mat-option>  
               </ng-container> 
            </mat-select>   
        </mat-form-field>

CodePudding user response:

You can add an element like a span, add it a ngFor looping on the first array, and then use your current ngFor to foop on the nested array.

So this would mean doing something like :

<mat-form-field appearance="outline">
  <mat-label>TestMat</mat-label>
  <mat-select placeholder="TestMat"  [formControl]="testControl"> 
      <span *ngFor="let mainArr of arrTmp">
        <mat-option *ngFor="let arr of mainArr" [value]="arr">
       {{arr.name}}
        </mat-option>           
      </span>
    </mat-select>   
</mat-form-field>
  • Related