目标:尝试设置下拉菜单的默认值(基于条件)
问题:删除ngModel时不起作用。但是,如果我重新添加并删除值,它也将无法正常工作。我以为ngModel应该是影响默认值的功能?
我尝试过的事情:
[我的理解是[]进行了属性绑定,并允许来自Typescript的信息显示在网页(html)上。 [()]允许双向绑定。和[ngModel]让您从TypeScript中获取值并显示它。因此,如果您可以使用ngModel进行2种方式绑定,那么值的目的是什么?
(上下文是具有表单的应用程序,在数据库的下拉列表中显示值,但允许用户更改值)。
下面是我的代码的一个最小示例:
HTML:
<mat-select [(ngModel)]="myRelationship" placeholder="Relationship to You" formControlName="relationship" required>
<mat-option *ngFor="let rel of relations" [value]="rel.value" (click)="selectRelationship(rel.value)">
{{ rel.viewValue }}
</mat-option>
</mat-select>
如果您的javascript对象具有相同的值但不同的viewValue,则默认值不起作用,例如:
relationships = [
{value: Cousin, viewValue: Primo },
{value: Cousin, viewValue: Prima } ]
条件逻辑
if (this.individual.Relationship.startsWith('Cousin')) {
if (this.individual.Gender == 'M') {
this.relations[indexCousin].viewValue = "Primo";
this.relations.push({ value: 'Cousin', viewValue: "Prima" });
}
}
您不应该在ngModel
上同时使用formControlName
和mat-select
的组合。其中之一就足够了。要设置默认值,可以使用[value]
元素上的mat-select
属性。您目前仅在mat-option
上有它。
<mat-option *ngFor="let rel of relations" [value]="rel.value" (click)="selectRelationship(rel.value)">
{{ rel.viewValue }}
</mat-option>
此模板中value
的目的是设置当选择一个选项时value
将具有的mat-select
。 output
上存在mat-select
事件,这些事件将为您提供所选选项的值。例如selectionChange
。
每个都有一个value属性,可用于设置如果用户选择此选项将被选择的值。的内容将显示给用户。
如果要设置value
的默认mat-select
。您可以使用[value]
,但是该组件在mat-select
组件上。
<mat-select [value]="myRelationship" placeholder="Relationship to You" required>
<mat-option *ngFor="let rel of relations" [value]="rel.value" (click)="selectRelationship(rel.value)">
{{ rel.viewValue }}
</mat-option>
</mat-select>
注意已删除formControlName
您可以使用formControlName
,但必须确保在组件中给formControl
一个值。
<mat-select placeholder="Relationship to You" formControlName="relationship" required>
<mat-option *ngFor="let rel of relations" [value]="rel.value" (click)="selectRelationship(rel.value)">
{{ rel.viewValue }}
</mat-option>
</mat-select>
设置formControl
的值的方式取决于在组件中如何实例化它。