angular - 从父组件以编程方式设置模型输入(信号)并对子组件的变化做出反应
在我的 Angular 16 应用中,我有一个父组件将 myObj(一个普通的 JavaScript 对象)传递给子组件,该对象被视为 model<MyObj>
<!-- parent.component.html -->
<app-children [myObjModel]="myObj"
(myObjModelChange)="doSomething($event)">
</app-children>
在我的子组件中,我将 myObj 作为模型输入处理:
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);
}
}
当我在子组件中修改值时,它运行正常,会触发 doThings() 函数。
如果我想在子组件中对值从父组件以编程方式改变时做出反应怎么办?(比如我在父组件中加载一个配置并将 myObj 传递给我的子组件,这应该触发一个函数)
如果父组件中的 myObj 发生变化,doThings() 函数不会被调用,即使我订阅了 myObjModel 的变化(使用 .subscribe() API)也不会触发。我在子组件中尝试过,但没有成功:
constructor() {
this.myObjModel.subscribe((val) => {
doThings(val);
});
}
我不想将model转换为input,因为我想利用双向绑定机制。
答案#1
您可以对模型输入使用 effect() 函数。根据文档:
在其他方面,你可以像使用标准输入一样使用模型输入。你可以通过调用 signal 函数来读取值,包括在像
computed和effect这样的响应式上下文中。
尝试以下内容
child.component.ts
export class Child {
public myObjModel = model<MyObj>();
constructor() {
effect(() => {
const myObj = this.myObjModel();
console.log('this.myObjModel change observed in effect()');
if (myObj) {
this.doThings(myObj);
}
});
}
onMyModelChange(event: MyObj) {
this.myObjModel.set(event);
}
doThings(myObj: MyObj) {
console.log('I changed value in: ', myObj);
}
}
工作示例:Stackblitz
