Mohammad Shadmehr
Mohammad Shadmehr

Reputation: 695

Angular 2 - pass object from parent to child component to modify

I know that sending an object from parent component to it children component is as easy as sending it through the @input.

In my case I need to send an object from parent to its child and have it changed at the child side and see this change in the parent side immediately.

In fact I want to send the reference of the object to the child not its value.

Upvotes: 2

Views: 6149

Answers (1)

HDJEMAI
HDJEMAI

Reputation: 9810

Here is an example of parent-child communication, we will see in the console that the changed value from child of the passed object from parent has changed.

Parent component:

import { Component, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <child [childProp]="parentProp" (childPropChange)="fromChild($event)"></child>
  `
})
export class AppComponent implements OnChanges {
  parentProp = {value1: "value1", value2: "value2"};

  ngOnChanges(c: SimpleChanges) {
    console.log('Parent changes: This doesnt happen often ', c);
  }

  fromChild(val) {
    console.log('Parent: receive from child, ', val.value1);
    console.log('Parent: receive from child, ', val.value2);
    console.log('Parent: receive from child, ', this.parentProp.value1);
    console.log('Parent: receive from child, ', this.parentProp.value2);
  }
}

Child component:

import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'child',
  template: `
    <h3>Child Component with {{childProp}}</h3>
    <button (click)="fire()">Talk to parent</button>
  `
})
export class ChildComponent implements OnChanges {
  @Input() childProp;
  @Output() childPropChange = new EventEmitter<{}>();

  ngOnChanges(changes: SimpleChanges) {
    console.log('in child changes with: ', changes);
  }

  fire() {
    this.childProp.value1 = "value1 changed";
    this.childProp.value2 = "value2 changed";
    this.childPropChange.emit(this.childProp);
  }
}

You can see the result in This stackblidtz

In the parent component we have this object:

parentProp = {value1: "value1", value2: "value2"};

In the child component, we change the received object from parent and emit the value this way:

this.childProp.value1 = "value1 changed";
this.childProp.value2 = "value2 changed";
this.childPropChange.emit(this.childProp);

You can see this result in the console:

Parent: receive from child,  value1 changed
Parent: receive from child,  value2 changed
Parent: receive from child,  value1 changed
Parent: receive from child,  value2 changed

Upvotes: 2

Related Questions