2

I am passing an object from parent to child. In child I am making changes to this object. Now , whenever I am making a change to this object in child, It should reflect in parent. For ex. while loading child component :

<child [record]="record"></child>

Now when I am changing record in child.I want it to reflect in parent.

any way to achieve this? thanks.

Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131

3 Answers3

5

The child component needs an @Input() and @Output() for two-way binding to work

@Component({
  selector: 'child',
  ...
})
export component MyChild {
  @Input() record;
  @Output() recordChange = new EventEmitter();

  updateRecord(newRecord) {
    this.record = newRecord;
    this.recordChange.emit(this.record);
  }
}

For [(record)]="...." to work it is important that input and output have the same base name ('record') and the output has the suffix Change otherwise you would need to longer syntax

[record]="..." (recordUpdated)="..." 

(assuming the output is named recordUpdated)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • can you provide a source for this information about having the same base name and the suffix `Change`? – Asqan Dec 14 '16 at 14:41
  • The docs mention it. That part was added a few weeks ago. Sorry only on the phone. I guess it's mentioned somewhere near template syntax or two-way-binding. – Günter Zöchbauer Dec 14 '16 at 14:54
0

Have you tried the banana in the box syntax:

 <child [(record)]="record"></child>
Harry Ninh
  • 16,288
  • 5
  • 60
  • 54
0

If you are not reassigning record in the child – i.e., you are not doing something like this.record = newRecord; – then what you have should work fine.

Since you are passing a JavaScript reference type (an object) to the child, any changes you make to the properties of the object in the child – e.g., this.record.property1 = someNewValue; – will be "seen" by the parent because both the parent and the child have a reference to the same record object. There is only one record object that is being manipulated.

If you are reassigning record in the child (or if record was instead a primitive type such as an integer, string, or boolean), then see @Günter's answer. In this case, there are multiple record objects involved, so you have to tell the parent when the child starts using a new object.

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492