Angular中Mat-Select遍历嵌套数组对象时如何正常显示name字段
[object Object] Display in Angular Mat-Select Hey there, let's get this sorted out! The root cause here is your arrTmp is a nested array—each entry in the outer array is itself an array of objects. Right now, your *ngFor is looping through the outer array, so each arr variable refers to an entire sub-array (like [{ "name": "name1", "id": "1" }]), not a single object. That's why trying to access arr.name gives you [object Object]—you're trying to get a property from an array, not the objects inside it.
Here are two straightforward solutions depending on what you need:
Solution 1: Flatten the Nested Data (Single List of Options)
If you just want all objects from the nested arrays to appear as individual options without grouping, flatten your data first in the component:
// In your component class arrTmp = [ [{ "name": "name1", "id": "1" }], [{ "name": "name2", "id": "2" }, { "name": "name3", "id": "2" }] ]; // Flatten the nested array into a single array of objects arrTmpFlattened = this.arrTmp.flat();
Then update your template to loop through the flattened array:
<mat-form-field appearance="outline"> <mat-label>TestMat</mat-label> <mat-select placeholder="TestMat" [formControl]="testControl"> <mat-option *ngFor="let item of arrTmpFlattened" [value]="item"> {{item.name}} </mat-option> </mat-select> </mat-form-field>
Solution 2: Use Optgroups for Grouped Options
If you want to keep the options grouped based on the original nested arrays, use Angular Material's mat-optgroup component to create sections for each sub-array:
<mat-form-field appearance="outline"> <mat-label>TestMat</mat-label> <mat-select placeholder="TestMat" [formControl]="testControl"> <!-- Loop through each group in the outer array --> <mat-optgroup *ngFor="let group of arrTmp" [label]="`Group ${group[0].id}`"> <!-- Loop through each object inside the group --> <mat-option *ngFor="let item of group" [value]="item"> {{item.name}} </mat-option> </mat-optgroup> </mat-select> </mat-form-field>
This will display each sub-array as a labeled group in the dropdown, with each object's name showing correctly.
Either approach will fix the [object Object] display issue—pick the one that fits your UI needs!
内容的提问来源于stack exchange,提问作者risky

