我有一个带日期选择器的表格。在输入数据的某些天,将显示其他字段。例如
<div *ngIf="ticketDate.getDay() === 0"
在此div内部,我将绑定到模型上的一些可选属性。但是,如果用户在输入数据后将日期选择器更改为其他日期,则div的内容将不再可见,但属性仍在模型中设置。
有没有一种惯用的方法来解除绑定*ngIf
为false时绑定的属性?
您可以#myDiv
在div
元素上设置模板参考变量:
<div #myDiv *ngIf="ticketDate.getDay() === 0">
并通过ViewChildren
和QueryList.changes
事件监视元素的存在。div
从DOM中删除时,可以重置模型属性:
@ViewChildren("myDiv") myDivList: QueryList<ElementRef>;
value1: string;
value2: string;
value3: string;
constructor(private changeDetectorRef: ChangeDetectorRef) { }
ngAfterViewInit() {
this.myDivList.changes.subscribe((list) => {
if (!list.length) {
this.value1 = undefined;
this.value2 = undefined;
this.value3 = undefined;
this.changeDetectorRef.detectChanges();
}
});
}
有关演示,请参见此堆叠闪电战。ChangeDetectorRef.detectChanges
调用该方法可防止Angular异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句