angular - 带 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 并且代码停止工作
解决方案
您的代码定义了两个表单控件。使用 时[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"
。
推荐阅读
- java - 获得 BYE JavaMail 异常:java.net.SocketTimeoutException:通过 apache camel 读取邮件时读取超时
- flutter - 高级网络图像
- linux-kernel - CentOS 内核启动选项前缀:rd vs inst
- flutter - Flutter 中的 Web 特定资源
- android - 使用 Tink 和 Google Cloud KMS 在 Android 上实现信封加密
- javascript - 如果模型中不存在数据,则使用 django 保存数据,如果数据存在则更新
- vue.js - Vue Routing - 防止重新渲染页面?
- html - 文本溢出 css 上的剩余边距
- r - 在同一个对象上应用相同的函数,使用不同的参数——整洁的方式
- r - 如何计算R中的最小生成树