piernik
piernik

Reputation: 3657

Creating custom form input in Angular

I'm creating my own form builder in angular. I have html code:

<form [formGroup]="formGroup">
    <my-input-field
            [field]="{type:'text'}"
            [formControlName]="'first'"></my-input-field>
</form>

I don't know how to in MyInputFieldComponent fetch parent's formGroup (I don't want to pass it as extra property. Less boilerplate is better). I can fetch parentElement itself, but how to get parent component to get it's formGroup ?

constructor(protected elementRef: ElementRef) {}

ngOnInit() {
   console.log(this.elementRef.nativeElement.parentElement);
}

Upvotes: 0

Views: 2078

Answers (1)

Rub&#233;n Soler
Rub&#233;n Soler

Reputation: 1187

Yo don't need to inject the parent component for this, in this case the best option is implement the ControlValueAccessor interface.

https://angular.io/api/forms/ControlValueAccessor

You can see how to do it here: https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

ControlValueAccessor is the interface to create custom form fields in Angular, if you implement it in your component @angular/forms can use it as a html native input, accessing the values with ngModel or formControlName

Upvotes: 3

Related Questions