我正在根据用户对位置或零件的更改,使用combineLatest
获取有关在partId
中存放在不同仓库(stockLocationId
)中的零件的某些信息数字。
这很好用,直到通过ViewChild
隐藏包含这些字段(又称为*ngIf
组件)的表单为止。这些组件的父容器上的*ngIf==false
是否导致重新创建了这些组件-如果是,是否有合理的方法来重新绑定valueChange
处理程序?
这是component.ts
的摘录,其中包含我的component.html
的动态组件,后跟我的combineLatest
方法。订阅者执行良好,直到我从行项目详细信息div
切换到购物车div
的视图,但返回编辑我的购物车中的项目后(重新显示这些字段),数量等库存信息不再在零件或位置字段的更改上触发。
@ViewChild('fldPart', { static: false }) fldPart: FieldComponent;
@ViewChild('fldStockLocation', { static: false }) fldStockLocation: FieldComponent;
...
combineLatest(
partIdField.valueChange.pipe(startWith(this.currentPartRequest.partId)),
locationIdField.valueChange.pipe(startWith(this.currentPartRequest.partRequestLocationId)),
(partId, stockLocationId) => { return { valid: partIdField.isValid && locationIdField.isValid, partId: <string>partId, stockLocationId: <string>stockLocationId }; }
).pipe(
debounceTime(250),
takeUntil(this.unsubscribe),
).subscribe(({ valid, partId, stockLocationId }) =>
{
// do stuff..
// works fine at first, but stops working after components hidden and reshown
console.log("value for partId or stockLocationId changed");
});
是否有比重新绑定valueChange
处理程序更好的方法,只要这些组件的容器切换为显示/隐藏即可。我可能并不总是知道何时会发生(尤其是从一般意义上讲;即:对于我正在研究的其他页面)。有没有办法强迫这些ViewChild引用保持不变,即使它们引用的组件被*ngIf
隐藏了?
答案 0 :(得分:1)
*ngIf
切换键销毁并重新创建组件
如果要有条件地隐藏组件,请使用[hidden]
而不是*ngIf
答案 1 :(得分:0)
*ngIf
从Dom中删除元素并销毁组件实例(调用生命周期钩子ngOnDestroy
。)。
您要么需要重新订阅新的“ valueChanges”,要么使用其他方式来隐藏您的元素。就像使用css'display:none'一样,它只会隐藏元素,而不会从Dom中删除元素。