* Ngfor在不同选择框中的多维数组

时间:2018-02-12 19:30:13

标签: angular multidimensional-array

我在使用子阵列/对象时有问题。

源是这样的数据(来自mongodb)

[{"_id":"5a7f49972df35835b8c6650a","manufacterer":"ManufactererA","name":"M1000","cpus":[{"name":"CPU0","desc":"test"},{"name":"CPU1","desc":"test1"},{"name":"CPU2","desc":"test2"},{"name":"CPU3","desc":"test3"}]},{"_id":"5a8001332df35841841f6a7b","manufacterer":"ManufactererA","name":"M2000"}]

这是模型服务器:

export class Server {
  _id?: string;
  manufacterer?: string;
  model?: string;
  cpus?: any;
}

他们得到了定义:

  server = new Server();
  servers: Server[] = [];
  manufacterers = [];

制造商被前一个选择框选中,没有任何错误。

在以下选择框中,用户选择模型。

    <mat-form-field *ngIf="manufactererValue">
        <mat-select placeholder="Model" name="model" [(ngModel)]="model">
          <mat-option *ngFor="let server of servers" [value]="server">
            {{server.name}}
          </mat-option> 
        </mat-select>
    </mat-form-field>

这很好用。现在我想在另一个选择框中再次迭代cpu-array。我仍然不明白如何迭代它的正确方法。这是我的工作代码:

    <mat-form-field *ngIf="manufactererValue && model"> 
        <mat-select placeholder="Cpu" name="cpu" [(ngModel)]="cpus">
          <mat-option *ngFor="let cpu of model.cpus" [value]="cpu">
            {{cpu.name}} + {{cpu.desc}}
          </mat-option>
        </mat-select>
    </mat-form-field>

示例:用户在第一个选择框(模型)中选择M1000,在下一个选择框中应显示相应的cpus "cpus":[{"name":"CPU0","desc":"test"},{"name":"CPU1","desc":"test1"},{"name":"CPU2","desc":"test2"},{"name":"CPU3","desc":"test3"}]等等...

即使Angular 2 using nested ngFor也无法帮助我

cpu选择框仍为空

1 个答案:

答案 0 :(得分:1)

首先需要将模型绑定到selected server,然后基于它,您可以知道需要在哪个数组中迭代以列出所有CPUs,所以这样的事情将起作用:< / p>

 <mat-form-field *ngIf="manufactererValue">
    <mat-select placeholder="Model" name="model" [(ngModel)]="server">
      <mat-option *ngFor="let server of servers" [value]="server">
        {{server.model}}
      </mat-option>
    </mat-select>
 </mat-form-field>

然后你的另一个表格字段:

<mat-form-field *ngIf="manufactererValue && server">
    <mat-select placeholder="Model" name="cpu" [(ngModel)]="cpu">
      <mat-option *ngFor="let cpu of server.cpu" [value]="cpu">
        {{cpu}}
      </mat-option>
    </mat-select>
 </mat-form-field>

修改

这是servercpu应该是这样的

let server: {_id?: string; manufacterer?: string; model?: string; cpu?: any[]};
let cpu: any;