【问题标题】:ngFor netsted array with objects in mat select optionngFor 嵌套数组与 mat 选择选项中的对象
【发布时间】:2021-12-06 08:46:06
【问题描述】:

我有带有选项选择的垫子表单字段

        <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>

其中 arrTmp =

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

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

]

结果在我的垫子表单字段中

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

如何正常显示arr.name?

【问题讨论】:

标签: angular typescript angular-material mat-form-field mat-select


【解决方案1】:

您需要为嵌套数组使用一个额外的 for 循环, 请看下面的代码

    <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>

【讨论】:

  • 我忘了 ng 容器,它也可以工作
【解决方案2】:

你可以添加一个像 span 这样的元素,在第一个数组上添加一个 ngFor 循环,然后使用你当前的 ngFor 循环嵌套数组。

所以这意味着做类似的事情:

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2013-03-27
    • 2018-10-14
    相关资源
    最近更新 更多