ngIf中的Angular 2+解除绑定属性

乔莫克

我有一个带日期选择器的表格。在输入数据的某些天,将显示其他字段。例如

<div *ngIf="ticketDate.getDay() === 0"

在此div内部,我将绑定到模型上的一些可选属性。但是,如果用户在输入数据后将日期选择器更改为其他日期,则div的内容将不再可见,但属性仍在模型中设置。

有没有一种惯用的方法来解除绑定*ngIf为false时绑定的属性

康纳斯·范

您可以#myDivdiv元素设置模板参考变量

<div #myDiv *ngIf="ticketDate.getDay() === 0">

并通过ViewChildrenQueryList.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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章