我有一个带有垫子选择和垫子选项的表单,我正在构建一个可重复使用的组件,我可以在其中编辑任何项目。我正在尝试填写表单默认值,但在查看文档 30 分钟并尝试各种操作后,我似乎无法以任何方式设置默认选择的选项。
<mat-form-field>
<mat-select [selected]="isSelected()" formControlName="category" placeholder="Select a category">
<mat-option *ngFor="let category of videoCategories | async" [value]="category.id">
{{ category.name }}
</mat-option>
</mat-select>
</mat-form-field>```
我已经尝试使用那个 [selected] 但它只是出错,因为它显然不是输入属性,尽管 it does show up in the documentation API here.
我认为这一定是可能的,否则它只会阻止任何带有 mat-select 的表单预填充“更新”功能。
我在 Angular 7 中使用 Angular Material 7。
编辑:
我的表单控件代码:
this.editVideoForm = new FormGroup({
title: new FormControl(this.videoTitle, [Validators.required, Validators.minLength(3), Validators.maxLength(50)]),
description: new FormControl(this.videoDescription, [Validators.required, Validators.minLength(5), Validators.maxLength(200)]),
category: new FormControl(this.categoryID, [Validators.required]),
link: new FormControl("https://vimeo.com/" + this.videoLink, [Validators.required, AddVideoValidators.mustBeVimeo, Validators.maxLength(100)]),
visibleToGuests: new FormControl(this.visibleToGuests, [Validators.required])
})
最佳答案
要选择一个值作为默认值,您需要为您的控件提供所需的值。
这里有一个 stackblitz 向您展示:https://stackblitz.com/edit/angular-gqw9yb?file=app/select-multiple-example.ts
export class SelectMultipleExample {
toppings = new FormControl('Mushroom');
toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
}
<mat-select placeholder="Toppings" [formControl]="toppings">
<mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
</mat-select>
关于Angular Material表单控件mat-select -- mat-option,设置更新项的默认选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53153197/