首页 > 解决方案 > 带 FormControl 的角垫选择触发器

问题描述

带垫选择触发器的角度材料选择下拉菜单。

尝试像这样创建选择下拉列表:

https://stackblitz.com/angular/omvmgjjbnnq?file=app%2Fselect-custom-trigger-example.ts

我的代码:

组件.ts


export class SelectCustomTriggerExample implements OnInit {
  dispForm : FormGroup
  constructor(private fb : FormBuilder) {}
  ngOnInit() {
    this.dispForm = this.fb.group({
        toppings : ['']
     })
  }


  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
}

组件.html

<mat-form-field>
  <form [formGroup]="dispForm">
  <mat-select placeholder="Toppings" formControlName="toppings" multiple>
    <mat-select-trigger>
      {{toppings.value ? toppings.value[0] : ''}}
      <span *ngIf="toppings.value?.length > 1" class="example-additional-selection">
        (+{{toppings.value.length - 1}} {{toppings.value?.length === 2 ? 'other' : 'others'}})
      </span>
    </mat-select-trigger>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>
  </form>
</mat-form-field>

我已将 formControl 更改为 formControlName 并且代码停止工作

标签: angular

解决方案


您的代码定义了两个表单控件。使用 时[formControl],您只使用其中之一:使用 . 创建的那个toppings = new FormControl();

使用时formControlName,您同时使用两者:使用创建toppings : ['']的一个是绑定到您的选择的一个,另一个是您的触发器使用的一个。

应该只有一个表单控件。并且所有代码都应该使用表单控件。

在您的组件中替换,

toppings = new FormControl();

经过

get toppings(): FormControl {
  return this.dispForm.get('toppings') as FormControl;
}

此外,您的表单名为dispForm,而不是dispform。它必须是formControlName="toppings",不是[formControlName]="toppings"

演示


推荐阅读