Jon Sud
Jon Sud

Reputation: 11641

Angular forms give no value accessor error when I pass formcontrol to child

Why I got an error "no value accessor for form control with unspecified name"?

I have edit-component:

html

 <mat-form-field>
  <input [formControl]="formControl">
 </mat-form-field>

ts:

 @Input formControl;

In the parent component (main-editor):

html:

<edit-component [formControl]="data">

ts:

get data() {
 return this.form.get('data');
}

constructor(private fb: FormBuilder) {
 this.form = this.fb.group({ data: [''] });
}

Upvotes: 0

Views: 349

Answers (2)

Abhishek
Abhishek

Reputation: 1778

In @Input() decorator we cannot provide formContolName as String. we can directly provide a formControl but remember this [AnyOtherName] instead of [formControl].

<form [formGroup]="form">
  <app-test [control]="form.controls.data"></app-test>
</form>

check it on a link:

https://stackblitz.com/edit/angular-9kpk3i?file=src%2Fapp%2Ftest%2Ftest.component.html

Upvotes: 0

keepwalking
keepwalking

Reputation: 2654

Its because [formControl] cannot be set on edit-component. If you add reactive inputs to a component you need to implement NG_VALUE_ACCESSOR.

Change <edit-component [formControl]="data"> with something else like <edit-component [myCustomFormControl]="data"> and

<mat-form-field>
  <input [formControl]="myCustomFormControl">
 </mat-form-field>

Upvotes: 1

Related Questions