Dan
Dan

Reputation: 57891

Piping `ngModel` from child component into parent

I'm trying to make [(ngModel)] work from inside child component. What I want in the end is to split the Big Complicated Form into Small Readable Forms. I hope this will make my code easier to understand.

Here's my not working code: https://plnkr.co/edit/UrTopLJ8RsZovltDkPiR?p=preview

I've forked my code from this very useful article: https://blog.thoughtram.io/angular/2016/10/13/two-way-data-binding-in-angular-2.html#creating-custom-two-way-data-bindings

I hope there is a way to nicely split big forms in angular 4.

Upvotes: 2

Views: 449

Answers (1)

AVJT82
AVJT82

Reputation: 73357

What you are missing is the getter and setter. Use them or then use ngModelChange to emit the modified value:

@Input() counter;
@Output() counterChange = new EventEmitter();

and then in template:

(ngModelChange)="counterChange.emit(counter)"

PLUNKER

As you mentioned, you'd use this with a form. What I suggest is that you'd use a model driven form, since then you wouldn't need this. You can build the form in the parent, and pass nested formgroups to the child(ren). Parent will be aware of the changes you make in the child without having to use @Output()

Here is a nice example of building Nested model driven forms with example of passing nested group to child component.

Upvotes: 1

Related Questions