I am setting a value from the parent component and changing it immediately. In the child component, change detection executes only once.
Parent's code: HTML
<h1>Parent Component</h1>
<p>Contents of the parent component</p>
<button (click)='parentClickEvt()'>Parent Button</button>
<child [message]="msg" (informParent)="parentWillTakeAction($event)"></child>
Parent's code: TS
export class ParentComponent {
msg: string="testing";
parentWillTakeAction(message) {
this.messageFromChild = message;
}
parentClickEvt() {
this.msg = "Message from parent to child";
this.msg = "India";
this.msg = "India, ASIA";
this.msg = "JAPAN";
this.msg = "JAPAN, ASIA";
}
}
Child's code: TS
export class ChildComponent implements OnInit {
@Input() message: string;
@Output() informParent = new EventEmitter();
ngOnChanges(simpleChanges: SimpleChanges) {
console.log(simpleChanges.message.currentValue)
}
}
Executing parentClickEvt method from parent is changing msg value 4 times. In child component, ngOnChanges is supposed to execute 4 times. But it is only executing once with the latest value.
Please suggest how ngOnChanges should execute according to all changes
v-patmentions in his answer. But I can't find a reason why one would want to do that. It's a very weird thing to do tbh. You can share in another question what do you want to use case you want to achieve and I'm sure there will certainly be a much better way to do so :)