shravs
shravs

Reputation: 41

Angular 10: How to update a parent component object in child component?

I am passing in an object abc from parent component to child component in Angular using @input decorator. I am updating some of the values in that object and need to update it in the parent component too. I tried 2-way binding using abcChange @output event emitter but that doesn't seem to be working. I'm not sure what I am missing here. Can someone please help to accomplish updating the abc object in the parent component from its child component?

Here's the code snippet I tried:

Parent component html:

<app-childcomponent [abc]="abc" [(abcChange)]="abcChange">

Child component ts:

 @Input() abc: Object;
 @Output() abcChange = new EventEmitter();
 this.abcChange.emit(this.abc);

Any help is greatly appreciated. Thank you in advance.

Upvotes: 0

Views: 1665

Answers (2)

Garuno
Garuno

Reputation: 2200

It looks like your are calling the this.abcChange.emit(this.abc); function once while the child component is instanciated. You need to call this method every time a change is made to abc for it to propagate to the parent component. Then in your parent component you can either have:

<app-childcomponent [(abc)]="abc">

for normal two-way data binding. Or you can do this:

<app-childcomponent [abc]="abc" (abcChange)="changeFunction($event)">

With this approach changeFunction is called every time a change is made to abc

Upvotes: 3

Luis Fernando
Luis Fernando

Reputation: 1294

The child components looks right.

But i thing you should check the parent template (html)

Should be something like:

parent.html:

<app-childcomponent [abc]="abc" (abcChange)="functionName($event)">

parent.ts:

 functionName(item: any) {
    this.localObj = item;   // <-- setting the object in parent
 }

Try this and i hope this works.

Upvotes: 0

Related Questions