[英]Angular 2+ unbind properties in ngIf
我有一个带日期选择器的表格。 在输入数据的某些天,将显示其他字段。 例如
<div *ngIf="ticketDate.getDay() === 0"
在此div内部,我将绑定到模型上的一些可选属性。 但是,如果用户在输入数据后将日期选择器更改为其他日期,则div的内容将不再可见,但属性仍在模型中设置。
是否有一种惯用的方式来解除绑定*ngIf
内部的*ngIf
如果为false)?
您可以在div
元素上设置模板引用变量#myDiv
:
<div #myDiv *ngIf="ticketDate.getDay() === 0">
并使用ViewChildren
和QueryList.changes
事件监视元素的存在。 当从DOM中删除div
时,可以重置模型属性:
@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异常。
您说您使用的是表单,如果使用的是ngModel
,则显然是模板驱动的表单。 您不能只使用[(ngModel)]
而是使用ngModel
。 这样就无需重置值。 如果模板的一部分不可见,则它将完全不包含在表单中。 如果那是一个合适的选择,我建议以下内容(演示是ConnorsFan的stackblitz的修改版本):
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm.value)">
<div *ngIf="ticketDate.getDay() === 0">
Value1: <input ngModel name="value1">
Value2: <input ngModel name="value2">
</div>
<button type="submit">Submit</button>
</form>
命名(所有)所需的表单字段,并在所需的结构中命名,以便在提交表单时,表单对象与所需的模型相对应。 因此,以上提交的表单值将是(如果条件为真):
{
"value1": "some value",
"value2": "some value"
}
演示: https : //stackblitz.com/edit/angular-sxwbsd? file = src%2Fapp% 2Fapp.component.html
PS:如果您需要在ts文件中引用表单,可以使用ViewChild
中所示的ViewChild
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.