Within my Angular 16 application, I have a parent component that passes a plain JavaScript object (myObj) to a child component, where it is treated as a model<MyObj>
.
<!-- parent.component.html -->
<app-children [myObjModel]="myObj"
(myObjModelChange)="doSomething($event)">
</app-children>
In the child component, I handle myObj as a model input:
export class ChildrenComponent {
myObjModel = model<MyObj>();
onMyModelChange(event: MyObj) {
this.myObjModel.set(event);
doThings(event)
}
doThings(event: MyObj) {
console.log("I changed value in: " + event);
}
}
Everything works well when I modify the value in my children component, triggering the doThings() function. But what if I want the children component to react when the value changes programmatically from the parent component? For example, loading a configuration in the parent and passing myObj to the children should trigger a function.
Currently, changing myObj in the father component does not call the doThings() function, even when subscribing to changes of myObjModel using the .subscribe() API.
constructor() {
this.myObjModel.subscribe((val) => {
doThings(val);
});
}
I prefer not to convert the model
to an input
because I want to take advantage of the two-way binding mechanism.