我的任务是创建一个帐户信息网页,该网页由 4 个预填字段(名字、姓氏、用户名和电子邮件)和底部的通用保存按钮组成。用户可以通过相应字段更改任何字段。我希望仅当用户更改任何字段时才启用保存按钮。任何跟踪状态变化的方法?我的代码如下:
<mat-card-content>
<div class="form-group">
<mat-form-field class="simple-form-field-50">
<input matInput placeholder="Given name" name="givenName" formControlName="givenName">
</mat-form-field>
<mat-form-field class="simple-form-field-50">
<input matInput placeholder="Family name" name="familyName" formControlName="familyName">
</mat-form-field>
<br>
<mat-form-field>
<input matInput placeholder="Email" name="email" formControlName="email">
</mat-form-field>
<br>
<button
[disabled]="waiting"
class="simple-form-button"
color="primary"
mat-raised-button
type="submit"
value="submit">
Save
</button>
</div>
</mat-card-content>
我的代码输出:
最佳答案
由于您使用的是响应式表单,因此您可以使用 valueChanges
在 FormGroup 上。
由于它是Observable
类型,您可以订阅
它来设置将在模板中使用的boolean
类型变量启用按钮。
...
@Component({...})
export class AppComponent {
form: FormGroup;
disableButton = true;
ngOnInit() {
...
this.form.valueChanges.subscribe(changes => this.disableButton = false);
}
}
在你的模板中:
<form [formGroup]="form">
...
<button [disabled]="disableButton">Submit</button>
</form>
更新:
如果你想在值没有真正改变时禁用它,请使用以前的值检查表单的当前值:
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
form: FormGroup;
disableButton = true;
userValue = {
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@domain.com'
}
ngOnInit() {
this.form = new FormGroup({
firstName: new FormControl(),
lastName: new FormControl(),
email: new FormControl()
});
this.form.patchValue(this.userValue);
this.form.valueChanges.subscribe(changes => this.wasFormChanged(changes));
}
private wasFormChanged(currentValue) {
const fields = ['firstName', 'lastName', 'email'];
for(let i = 0; i < fields.length; i++) {
const fieldName = fields[i];
if(this.userValue[fieldName] !== currentValue[fieldName]) {
console.log('Came inside');
this.disableButton = false;
return;
}
}
this.disableButton = true;
}
}
注意:StackBlitz 已相应更新。
Here's a Working Sample StackBlitz for your ref.
关于javascript - 如何检查 Angular 4/6 的状态变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53943329/