Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 @Input property update does not affect the UI

There are 2 components: parentComponent and ChildComponent, which is defined inside the parent. In the parentComponent there is a local variable which is used as value to pass to an input property of the ChildComponent (using a getter).

ParentComponent.ts:

@Component({
selector:'parent-component',
template:`
<h1>parent component</h1>
<child-component [personData]="PersonData"></child-component>
`
})
export class ParentComponent{
personData:Person;

get PersonData():Person{
return this.personData;
}

set PersonData(person:Person){
this.personData = person;
}

ngOnInit(){
this.PersonData = new Person();
this.PersonData.firstName = "David";
}

//more code here...

}

ChildComponent.ts:

@Component({
    selector:'child-component',
    template:`
    <h1>child component</h1>
    <div *ngIf="personData">{{personData.firstName}}</div>
    `
    })
export class ChildComponent{
    @Input() personData:Person;        

    //more code here...

 }

The issue is: in some place in the parent component, when specific event occurs, a function newPersonArrived(newPerson:PersonData) is being called, the function code is as following:

newPersonArrived(newPerson:Person){
    this.PersonData = newPerson;
    }

This doesn't affect the UI with the new person name!

Only the following helps:

newPersonArrived(newPerson:Person){
    this.PersonData = new Person();
    this.PersonData.firstName = newPerson.firstName;
    }

Is this the expected behavior?

why only when the personData is initialized to new Person, the UI "catches" the change?

like image 861
Batsheva Avatar asked May 09 '17 06:05

Batsheva


Video Answer


1 Answers

please watch for your changes in child component

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

@Component({
    selector:'child-component',
    template:`
    <h1>child component</h1>
    <div *ngIf="personData">{{personData.firstName}}</div>
    `
    })
export class ChildComponent implements OnChanges{
    @Input() personData:Person; 
     public ngOnChanges(changes: SimpleChanges) {
          if ('personData' in changes) {
              //some code here
           }
      }       

    //more code here...

 }
like image 192
sainu Avatar answered Oct 04 '22 03:10

sainu