0

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);
}
2
  • Hmm... Why would you want to do that? Get the value of the formgroup? Why not pass the name as an @input itself? What's stopping you and what's the usecase/need? Commented Mar 13, 2018 at 10:53
  • Without that I would have to give extra attribute in all my-input-field. It's redundant in my opinion. formControlName directive knows if parent component has formGroup so it has to be possible. Commented Mar 13, 2018 at 11:14

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I could use that aproach. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.