Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将*ngFor指令放在mat select标记或mat option标记中更好吗?_Angular - Fatal编程技术网

Angular 将*ngFor指令放在mat select标记或mat option标记中更好吗?

Angular 将*ngFor指令放在mat select标记或mat option标记中更好吗?,angular,Angular,考虑两种不同的方法来生成一个mat select下拉显示,其中包含来自数组的多个选项。在本例中,optionList位于.ts文件中 something.component.html 两个html块似乎具有完全相同的功能。那么,有没有更好的/标准的做事方式?一个比另一个有优势吗 谢谢这两个HTML块似乎具有完全相同的功能 不,它们没有相同的功能。第一个选项重复整个选择,这将导致mat form字段中出现多个下拉列表。您只需要重复选项元素,因此第二个选项就是要做的 一个比另一个有优势吗 很明显,从

考虑两种不同的方法来生成一个mat select下拉显示,其中包含来自数组的多个选项。在本例中,optionList位于.ts文件中

something.component.html

两个html块似乎具有完全相同的功能。那么,有没有更好的/标准的做事方式?一个比另一个有优势吗

谢谢

这两个HTML块似乎具有完全相同的功能


不,它们没有相同的功能。第一个选项重复整个选择,这将导致mat form字段中出现多个下拉列表。您只需要重复选项元素,因此第二个选项就是要做的

一个比另一个有优势吗

很明显,从上面这一点,我们可以得出结论,第二个有效,第一个无效

只需将这些HTML块插入一个简单的函数,并将一个数组分配给optionList,您就会看到第一个函数不能按预期工作,并产生一个奇怪的结果

自从我使用长度为4的optionList以来,创建了四个select元素

结论


使用第二个HTML块查看文档。

为什么不使用第二个最接近材料网站示例的HTML块呢?第一个HTML块反复重复整个选择列表。
<!-- Place the *ngFor in mat-select-->
<mat-form-field>
  <mat-label>Dropdown</mat-label>
  <mat-select *ngFor="let option of optionList;"  [(value)]="selectedOption">
    <mat-option [value]="option">
      {{option}}
    </mat-option>
  </mat-select>
</mat-form-field>

<!-- Place the *ngFor in mat-option -->
<mat-form-field>
  <mat-label>Dropdown</mat-label>
  <mat-select [(value)]="selectedOption">
    <mat-option *ngFor="let option of optionList;" [value]="option">
      {{option}}
    </mat-option>
  </mat-select>
</mat-form-field>