首页 文章

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

提问于
浏览
3

我有一个带有垫选项的垫子选项,我正在构建一个可重复使用的组件,我可以在那里编辑任何项目 . 我正在尝试填写表单默认值,但在文档中查找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>```

我've tried to use that [selected] but it just errors out as apparently it'不是输入属性虽然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 回答

  • 2

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

    这是一个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>
    

相关问题