首页 > 解决方案 > 当列表初始化为空时,使用 ngFor 创建 mat-option 元素

问题描述

当我在我的“能力”mat-select 中选择一项技能时,我想更新“specialisation”mat-select”中的值。我将我的 var 与使用的模型相关联,[(ngModel)]但它不会更新列表。

我尝试使用具有角度和材料 7 的 ngModel。

HTML:

<mat-form-field>
  <mat-select name="competence_1_name" [(ngModel)]="competence_1.name">
    <mat-option>-- Faites un choix --</mat-option>
    <mat-option *ngFor="let competence of competences" value="{{competence.name | lowercase}}">{{competence.name}}</mat-option>
  </mat-select>
  <mat-label>Compétence</mat-label>
</mat-form-field>
[...]
<mat-form-field>
  <mat-select name="competence_1_spe_1" [(ngModel)]="competence_1.specialisation_1">
    <mat-option>-- Faites un choix --</mat-option>
    <mat-option *ngFor="let specialisation of competence_1.specialisation_list" value="{{specialisation | lowercase}}">{{specialisation}}</mat-option>
  </mat-select>
  <mat-label>Spécialisation</mat-label>
</mat-form-field><br>

主类:

export class GeneratePnjComponent implements OnInit {

    competences: Array<Competence>;
    masteries: Array<string>;
    competence_1 = new Competence("");
    competence_2 = new Competence("");
    competence_3 = new Competence("");
    name: string;
    cost: number;
    time: number;
    ...
}

技能等级:

export class Competence {
    name: string;
    mastery: string;
    specialisation_1: string;
    specialisation_2: string;
    specialisation_list: Array<string>;

    constructor(name: string) {
        this.name = name;
        this.specialisation_list = new Array<string>();
    }
}

预期结果:当我在列表“competence_1_name”上选择一个值时,列表“competence_1_spe_1”会更新

实际结果:即使我在列表 'competence_1_name' 中选择一个值,列表 'competence_1_spe_1' 中也没有值

标签: angularangular-materialngfor

解决方案


可能与此重复

您需要使用此语法,[value]="competence.name"但我不知道您是否可以使用管道| lowercase

您可以考虑用[(ngModel)]FormControls FormGroups 或 FormBuilder 替换。这会给你更多的灵活性。


推荐阅读