[英]'No value accessor for form control with name' while creating reusable matInput component with ControlContainer
我正在使用ControlContainer
按照本指南創建可重用表單,成功創建了一個可重用表單組,但是當我嘗試使用matInput
創建可重用表單元素時,遇到了No value accessor
錯誤。 這是my-form-field.ts
文件:
import { Component, Input, OnInit } from '@angular/core';
import {
ControlContainer,
FormBuilder, FormControl,
FormGroup,
FormGroupDirective,
} from '@angular/forms';
@Component({
selector: 'my-form-field',
template: `
<mat-form-field>
<mat-label>{{label}}</mat-label>
<input matInput [formControlName]="formControlName">
</mat-form-field>
`,
viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }],
})
export class MyFormFieldComponent implements OnInit {
@Input() formControlName: string;
@Input() label: string;
formGroup: FormGroup;
constructor(private ctrlContainer: FormGroupDirective, private formBuilder: FormBuilder) {
}
ngOnInit(): void {
this.formGroup = this.ctrlContainer.form;
const control = new FormControl('');
this.formGroup.addControl(this.formControlName, control);
}
}
這是我如何使用它:
<form [formGroup]='formGroup'>
<my-form-field label='Test' formControlName='name'></my-form-field>
</form>
在此處重新創建示例: https : //stackblitz.com/edit/angular-9-material-reusable-matinput? file = src/app/my-form-field.ts
我的方法可能是錯誤的,因此對可重用 matInput 表單組件的建議也可以。
您正在使用@Input
formControlName
名稱,這會使 Angular @Input
formControlName
,請使用另一個名稱,例如controlName
<my-form-field label='Test' controlName='name'></my-form-field>
並在輸入
@Input('controlName') formControlName: string;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.