I'm following this guide with ControlContainer
to create reusable forms, successfully created a reusable form group but when I tried to create reusable form element with matInput
, encountered the No value accessor
error. Here's the my-form-field.ts
file:
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);
}
}
And here's how I use it:
<form [formGroup]='formGroup'>
<my-form-field label='Test' formControlName='name'></my-form-field>
</form>
Recreated the example here: https://stackblitz.com/edit/angular-9-material-reusable-matinput?file=src/app/my-form-field.ts
My approach could be wrong, so a suggestion for reusable matInput form component is ok too.
You're using as name of the
@Input
formControlName
, this makes Angular confussed, use another name, e.g.controlName
And in Input