【问题标题】:Angular Material form controls mat-select -- mat-option, setting the default option for updating items?Angular Material表单控件mat-select --mat-option,设置更新item的默认选项?
【发布时间】:2018-11-05 11:08:31
【问题描述】:

我有一个带有垫子选项的垫子选择的表单,我正在构建一个可重复使用的组件,我可以在其中当场编辑任何项目。我正在尝试填写表单默认值,但是在查看文档 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])
})

【问题讨论】:

  • selected 不是 doc 中的输入属性。它返回“当前选择的选项”。如 API 文档中所述。

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


【解决方案1】:

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

这是一个堆栈闪电向您展示: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>

【讨论】:

  • 我已经这样做了,已经将代码更新到我的表单控件,我正在控制台。记录它的值,表单控件确实具有正确的值,但是该选项确实没有被选中 :(
  • 您看到它在我的闪电战中有效,但在您的闪电战中无效:在这种情况下,您需要提供 minimal reproducible example 来重现该问题;要么你自己发现你的错误来解决它,要么我有一些在我面前不起作用的东西,我可以纠正。
  • 您的示例帮助解决了我的问题。事实证明,我一直在基于类别的全局变量而不是我插入可重用组件的本地输入属性在前端创建值。我已经让全局类别进入,但已将默认值添加为静态类别选项。现在我将该默认值作为重复值。将尝试找到解决方法,但即使这样也应该没问题。
  • 看,你自己解决了 :) 我建议你删除你的问题,因为这是你的错误,以后其他人很难重现。如果你不这样做,那么感谢你的声誉,无论如何,祝你的项目好运!
  • 我认为这不适用于 formGroup 即模型驱动的表单,是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-03
  • 1970-01-01
  • 2018-05-15
  • 2018-11-12
  • 2018-08-17
  • 2020-03-09
  • 2020-12-05
相关资源
最近更新 更多