I want to create a custom input component that I can use with the FormBuilder API. How do I add formControlName inside a component?
Template:
Definitely worth diving deeper into @web-master-now's answer but to simply answer the question you just need the ElementRef to reference the formControlName to the input.
So if you have a simple form
this.userForm = this.formBuilder.group({
name: [this.user.name, [Validators.required]],
email: [this.user.email, [Validators.required]]
});
Then your parent component's html would be
Then in your custom component custom-input.ts
import { Component, Input, ViewChild, ElementRef } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'custom-input',
templateUrl: 'custom-input.html',
})
export class YInputItem {
@Input('label') inputLabel: string;
@Input() control: FormControl;
@ViewChild('input') inputRef: ElementRef;
constructor() {
}
ngAfterViewInit(){
// You should see the actual form control properties being passed in
console.log('control',this.control);
}
}
And then in the component's html custom-input.html
Definitely worth checking out the ControlValueAccessor, but depending on how you are developing the control you might want to just use @Output to listen to change events , i.e if different inputs in the form have different events, you can just put the logic in the parent component and listen.