Allan Juan
Allan Juan

Reputation: 2554

How to pass ngForm to child component?

I have a custom input component that I want to reuse in several forms. But how can I pass the parent's form context to it? I already managed to do this with reactive forms by passing the FormGroup instance and the name of the field. I'm trying to achieve the same with template driven forms but I had no success so far. This is my code:

<!-- parent.component.html -->
<form #form="ngForm" (ngSubmit)="console.log(JSON.stringify(f.value))">
  <input name="someField" ngModel />
  <app-child name="myField"></app-child>
  <button type="submit">Submit</button>
</form>
<!-- child.component.html -->
<input ngModel [name]="name" />
// child.component.ts
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
})
class ChildComponent {
  @Input() name: string;
}

The binding didn't went right, since when the form is submitted f.value.myField is not defined, only f.value.someField. How can I achieve this?

Upvotes: 1

Views: 2029

Answers (1)

OLO
OLO

Reputation: 471

You can use ngModelGroup directive then provide it in your child component like below and here is a working stackblitz :

<form #form="ngForm" (ngSubmit)="console.log(JSON.stringify(f.value))">
  <input name="someField" ngModel />
  <app-child ngModelGroup="myField"></app-child> // here
  <button type="submit">Submit</button>
</form>
// child.component.ts
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  viewProviders: [{provide: ControlContainer, useExisting: NgModelGroup}] // here
})
class ChildComponent {
  @Input() name: string;
}

Upvotes: 1

Related Questions