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?
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With