【发布时间】:2025-11-24 09:35:01
【问题描述】:
我有与this question 类似的问题,但似乎该问题已过时,因为这两个答案都不适合我。
子组件只是从一个名为 Proposal 的复杂对象中渲染数据,作为输入传递(它根本没有用户控件,因此不需要触发任何事件或传递任何东西)。
@Component({
selector: 'fb-proposal-document',
templateUrl: './proposal-document.component.html',
styleUrls: ['./proposal-document.component.css']
})
export class ProposalDocumentComponent implements OnInit, OnDestroy {
@Input() proposal: Proposal;
constructor()
}
模板的相关部分是这样,迭代一个数组并检查一个属性以使用*ngIf显示不同的文本:
<li class="section" *ngFor="let qp of proposal?.quoted_products">
<li class="section" *ngFor="let room of qp?.rooms">
...
<div class="row">
<div class="col-md-12">
Supply
<span *ngIf="room.is_fitted">
and install
</span>
<span *ngIf="!room.is_fitted">
only
</span>
</div>
</div>
...
</li>
</li>
在父级中,用户可以单击复选框将“is_fitted”更改为 true 或 false。父级使用域驱动器形式。在父级的ngOnInit 中是这样的代码:
this.myForm.controls['isFitted'].valueChanges.subscribe(
value => {
this.proposal.is_fitted = value;
let qp = this.proposal.quoted_products[this.qpCurrentIndex];
qp.rooms.forEach(function(room) {
room.is_fitted = value;
});
}
);
正确更新属性。我可以看到,如果我console.log 它。所以问题是,当嵌入的room.is_fitted 值发生变化时,如何让孩子重新触发/重新处理*ngIf?
我已经尝试使用 ViewChild 实现this idea,所以 ngOnInit 中的上述代码变为:
this.myForm.controls['isFitted'].valueChanges.subscribe(
value => {
this.proposal.is_fitted = value;
let qp = this.proposal.quoted_products[this.qpCurrentIndex];
qp.rooms.forEach(function(room) {
room.is_fitted = value;
});
this.proposalDocument.notifyChange(this.proposal);
}
);
但这也不起作用。我在 child 中的 notifyChange 调用成功:
notifyChange(proposal: Proposal) {
console.log('I changed');
this.proposal = proposal;
}
但视图没有更新 - *ngIf 逻辑没有得到重新处理。
【问题讨论】:
-
@JBNizet 感谢提供有用的链接,除了没有解释的内容(Angular Docs LifeCycle Hooks 部分中也没有)是如何强制 ngIf 重新处理对象并导致视图更新。跨度>
标签: angular angular2-components angular2-changedetection