【问题标题】:How to Iterate the options of the mat-select tag?如何迭代 mat-select 标签的选项?
【发布时间】:2020-01-16 17:41:45
【问题描述】:

我正在尝试迭代两个数组,一个用于创建必要的选择字段,另一个用于填充每个选择字段中显示的选项。

 <div *ngFor="let subject of subjects" class="input-field col s6"> //iterating through all the subjects
   <mat-form-field>
      <mat-label>{{subject}}</mat-label> /*creating select-field for each subject*/
         <mat-select [(value)]="selectedStaff">
             <mat-option *ngFor="let faculty of facultyNames" [value]="faculty" > /*iterating facultyNames to populate options*/
                 {{faculty}} /*populating options*/
             </mat-option>
         </mat-select>
     </mat-form-field>
  </div>

选择字段和选项按预期生成,但是当我在选择字段中选择一个选项时,其他选择字段的所有值也会更改为相同的选项。我无法为每个选择字段单独选择选项。

我刚刚开始学习 Angular,我找不到其他方法来实现它。 任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: angular typescript angular-material ngfor


    【解决方案1】:

    问题是你所有选择的值都相同。

    改变这个。

    <div *ngFor="let subject of subjects" class="input-field col s6">
    

    <div *ngFor="let subject of subjects; let i = index" class="input-field col s6">
    

     <mat-select [(value)]="selectedStaff">
    

    对于

     <mat-select [(value)]="selectedStaff[i]">
    

    在您的 ts 中,attr selectedStaff 需要是一个数组,subjects 的每个项目都有一个值,或者尝试使用空数组进行初始化。

    【讨论】:

    • 谢谢@ManuelPanizzo!完美运行!我是 Angular 的新手,我正在学习它,您是否推荐任何用户友好且具有最常用 ng-directives 的语法和用法的网站?
    • 在youtube上有很多免费课程。但是,如果您可以在 udemy.com 支付 10 到 11 美元,那么您就有很多很棒的 Angular 课程!我在那里学到的。
    • 谢谢!我会调查的。
    猜你喜欢
    • 1970-01-01
    • 2019-06-03
    • 2021-01-16
    • 1970-01-01
    • 2022-10-15
    • 2019-07-03
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    相关资源
    最近更新 更多