Working with angular 7 and Bootstrap 4, I want to wrap my bootstrap 4 inputs in a custom component in order to reduce the boilerplate in my templates.
I want that the fi
The "key" is using viewProvider. You use a @Input set to give value to a formControl, see stackblitz. The "magic" is that if equal refered to formControl in the "children" or form.get('input1') in the parent
@Component({
selector: 'app-form-control',
template: `
{{formControl.valid}}{{formControl.touched}}}
`,
viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]})
export class HelloComponent {
formControl: FormControl;
constructor(private parentF: FormGroupDirective) { }
@Input()
set controlName(value) {
this.formControl = this.parentF.form.get(value) as FormControl
}
@Input() label: string;
@Input() placeholder: string;
}
And call the component this way:
Update well, (after a year) take account the stackblitz was erroneous. when you (click) in buttons create a new Form:
this.form=this.createForm({note:'lll'})
This "break" the relationship between the component and the form because the relation is about the older form -only change if change the @Input "nameControl". So the correct is use a setValue to give a new value to the form.