1

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?

Allan Juan
  • 2,048
  • 1
  • 18
  • 42

1 Answers1

1

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;
}
OLO
  • 471
  • 4
  • 7
  • Hmm... when I do so, `f.value.myField` evaluates to `{}` instead of undefined. That's a start. The editor also complains with `"No provider for ControlContainer"` (in `parent.component.html`), but the code runs fine. – Allan Juan Feb 18 '21 at 19:27
  • 1
    give me a few minutes i'll post a working stackblitz – OLO Feb 18 '21 at 19:29
  • No hurries, my work day is already over . Thanks in advance! – Allan Juan Feb 18 '21 at 19:30
  • i added the link in the answer – OLO Feb 18 '21 at 19:49
  • It works. Thank you! However, it isn't quite what I was looking for. This one fits my needs better: https://stackoverflow.com/questions/50618050/how-to-create-custom-input-component-with-ngmodel-working-in-angular-6/50723598 – Allan Juan Feb 19 '21 at 15:43