【发布时间】:2018-09-13 11:24:26
【问题描述】:
我正在使用 Angular 表单,我想使用它们内置的更改检测来在我的应用程序中实现一项功能。当用户点击一个按钮时,只有在他/她对表单进行了任何更改时,他才会看到一个对话框。
我有 changesMade 变量:
private changesMade: boolean;
这是我的 TS 代码形式:
this.carForm = new FormGroup({
name: new FormControl('', [
Validators.required,
Validators.pattern('[a-zA-Z ]*'),
Validators.minLength(1),
Validators.maxLength(10)
])});
这是我的表单 HTML 代码:
<form [formGroup]="carForm">
<ion-item>
<ion-label stacked>car name</ion-label>
<ion-input type="text" [(ngModel)]="carname" formControlName="name"></ion-input>
</ion-item>
</form>
这是我的模拟(目前)服务调用,我在设置绑定到输入的 carname 的值后订阅表单更改
setTimeout(()=>{
this.carname = "BMW";
this.carForm.valueChanges.subscribe(val => {
this.changesMade = true;
});
}, 44)
这里的问题是,即使我没有触摸表单,this.changesMade 也会设置为 true。
注意:如果我在 ngAfterViewInit 中移动代码的 subscribe 部分,即使我没有修改输入,它仍然会将 changesMade 设置为 true:
ngOnInit(){
//simulated server call
setTimeout(()=>{
this.carname = "BMW";
}, 44)
}
ngAfterViewInit(){
this.carForm.valueChanges.subscribe(val => {
this.changesMade = true;
});
}
我创建了一个STACKBLITZ 来演示这个问题。仅当我实际触摸 UI 中的输入时,如何才能使其执行 this.changesMade = true;?
【问题讨论】:
-
为什么要手动设置 this.carname = "BMW"?由于您正在设置此值更改检测被触发并且您的标志变为真。如果您使用的是响应式表单,请删除 [(ngModel)]="carname"。
标签: angular ionic-framework rxjs ionic3 angular-forms