I have an input component customInput
that creates a classic input field and adds some layouting-spice to it, no additional logic.
I want to pass a formControl to it, to bind it to the input it contains.
Should be used like this:
<form [formGroup]="form">
<custom-input [formControl]="form.controls['control']"></custom-input>
</form>
Inside Custom Input:
export class HidInputFieldComponent {
@Input() formControl: AbstractControl
...
}
<div class="container">
<input [formControl]="formControl"/>
<label>label</label>
</div>
Now when i initialize the component, i get
No value accessor for form control with unspecified name
Logging the control in my components constructor, it is undefined.
Am I doing it wrong or isn't there a way around ControlValueAccessor
? Since I am not actually building a custom control (I still use classic input) it seems extreme
You don't need to import ControlValueAccessor or anything similar to accomplish that.
All you need to do is to pass the FormControl object to your child component like this:
<form [formGroup]="form">
<custom-input [control]="form.controls['theControlName']">
</custom-input>
</form>
That means your custom-input component should look like this:
import {Component, Input} from '@angular/core';
import {FormControl} from '@angular/forms';
@Component({
selector: 'custom-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.scss']
})
export class InputComponent {
@Input() control: FormControl;
}
And the template:
<input [formControl]="control">
And that's it.
If you implement the custom input like that you won't have to bring the parent formGroup into the child component logic, it is completely unnecessary there (Unless you need to make some operations on it or on some of the rest of form controls).
Besides, passing the FormControl object to the custom input would give you access to the properties of it without referencing the FormGroup and then getting the specific control, because that's a work done on the parent component.
I hope this solution helps to simplify the work of many people as it's pretty common to make this kind of custom controls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With