Gabriel
Gabriel

Reputation: 821

formControlName in a child component

I would like to create a custom input component and reuse it in my forms, but I am hitting an issue with formGroup and formControlName.

// Form
<form [formGroup]='loginForm'>
  <custom-input [myFormControlName]='email'></custom-input>
</form>

// CustomInput Component's Template
<input formControlName='myFormControlName'>

The problem appears to be that formControlName is expecting to be used with a FormGroup directive and since I am using formControlName in a sub-component it doesn't find the formControlName.. Anyone knows how to work around that?

Upvotes: 34

Views: 30587

Answers (4)

Sof&#237;a
Sof&#237;a

Reputation: 914

Like @MassimoVariolo's article mentions, you can pass the form as an input to the child component.

Parent component html:

<child-component [form]="form"></child-component>

Child component ts file:

@Input() public form: FormGroup;

Child component html (you need the div with the formGroup, otherwise you'll get an error):

<div [formGroup]="form">
    <input formControlName="myFormControlName"> 
</div>

Upvotes: 22

Gh111
Gh111

Reputation: 1452

I know two ways how it's possible to implement this behavior, one was mentioned by Sofia in the answer above, the second approach is to pass formControl down to the child component!

Inside parent component HTML

<child-component
   [control]="parentForm.get('form-control-name-you-want-to-pass-down')">
</child-component>

Inside child-component

@Input() control: AbstractControl = new FormControl();

Inside child component HTML

<input [formControl]="control" />

Upvotes: 11

Massimo Variolo
Massimo Variolo

Reputation: 4777

You can consider reading this useful article: Using Child Components in Angular Forms

The core of the solution is to pass the formGroup instance to the child component and wrap it with the formGroup itself.

Upvotes: 2

alexKhymenko
alexKhymenko

Reputation: 5608

You need to implement control value accessor in your child component read more here https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

Upvotes: 14

Related Questions