'Pass FormControl to a child that has a child that uses ControlValueAccessor in Angular
I'm developing a Mobile App using Ionic + Angular using ReactiveForms.
I have a base input-form-control component that I use across the application. This component implements ControlValueAccessor and facilitate the process.
I will show short snippets of the code to explain the idea...
@Component({
selector: 'app-input-form-control',
templateUrl: './input-form-control.component.html',
styleUrls: ['./input-form-control.component.scss']
})
export class InputFormControlComponent implements ControlValueAccessor, DoCheck { }
Example of use from a parent:
<app-input-form-control formControlName="test">
</app-input-form-control>
All good so far.
Now, I have a requirement to add more functionality to an input. Let's say by adding a button below it to open a modal, choose a phone number from a list and add it as the value of the input.
For me, this is a new component that can be used across the app. Let's create it to explain my issue:
@Component({
selector: 'app-phone-number-form-control',
templateUrl: './phone-number-form-control.component.html',
styleUrls: ['./phone-number-form-control.component.scss'],
})
export class PhoneNumberFormControlComponent {
constructor(
public ngControl: NgControl
) {
}
}
I know that I need and input, which I have already (remember the previous base input that I've shown) and a button below it.
./phone-number-form-control.component.html
// This is my base input from before
<app-input-form-control
[(ngModel)]="ngControl"> // Note here...
</app-input-form-control>
// This is the new requirement of the feature
<ion-button>Open modal</ion-button>
Example of use:
<app-phone-number-form-control
formControlName="phoneNumber">
</app-phone-number-form-control>
I received:
ERROR Error: No value accessor for form control with name: 'phoneNumber'
I don't know how to pass the FormControl from app-phone-number-form-control to app-input-form-control.
I have tried to follow other topics that talks about this, but they only reached until the creation of app-input-form-control. In my case, I have another component as an intermediate.
My goal is to be able to create a component that uses my base input (app-input-form-control) and pass it the FormControl.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
