Angular Material表单控件mat-select-mat-option,设置用于更新项目的默认选项吗?

时间:2018-11-05 11:08:32

标签: angular angular-material angular-reactive-forms angular-forms angular-material-7

我有一个带有选择垫和垫选项的表格,并且正在构建一个可重用的组件,可以在其中编辑任何项目。我正在尝试填写表单的默认值,但是在文档中查找了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 Material 7和Angular 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])
})

1 个答案:

答案 0 :(得分:3)

要选择一个默认值,您需要为控件提供所需的值。

这里是一次闪电战,向您展示: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>