gpt4 book ai didi

带 FormControl 的 Angular Mat 选择触发器

转载 作者:行者123 更新时间:2023-12-02 19:53:04 24 4
gpt4 key购买 nike

带有垫子选择触发器的 Angular Material 选择下拉列表。

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

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 : [''] 创建的一个是绑定(bind)到您的选择的一个,另一个是您的触发器使用的那个。

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

在您的组件中替换,

toppings = new FormControl();

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

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

Demo

关于带 FormControl 的 Angular Mat 选择触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57747340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com