我有一些表格和按钮来保存它。仅当表单上有未保存的更改(输入)时,才必须启用该按钮。
<form>
<div>
... (inputs)
<span (click)="save()"> Save </span>
</div>
</form>
Angular 5中是否有一些内置机制用于表单脏检查?实现此方案的最简单方法是什么?
是,有,我强烈建议您看看documentation of reactive forms。
此外,内置机制仅用于检查表单的状态:
touched
表示用户已输入表格dirty
/ !pristine
表示用户进行了修改但是,如果您要处理所做的更改,则不应使用该方法:如果您的用户名将其用户名从“ foo”更改为“ bar”,然后又更改为“ foo”,则您的表单没有任何更改,因此用户不必发送上述表格。
相反,我建议您做一个函数,将表单与对象的原始值进行比较。这是您的操作方法:
// Creates a reference of your initial value
createReference(obj: any) {
this.reference = Object.assign({}, obj);
}
// Returns true if the user has changed the value in the form
isDifferent(obj: any, prop: string) {
return this.reference[prop] !== obj[prop];
}
submitForm(form: any) {
// ... Business code ...
hasChanges = false;
for (let prop in form) {
if (this.isDifferent(form, prop)) { hasChanges = true; }
}
// If no changes, cancel form submition
if (!hasChanges) { return; }
}
当您使用反应式表单(https://angular.io/guide/reactive-forms)时,表单组和控件上分别具有属性pristine
和属性dirty
。应该看起来像这样:
<form form-group="myGroup">
<div>
<input type="text" formControlName="ctrl1">
... (further inputs)
<span><button (click)="save()" [disabled]="myGroup.pristine"> Save </button></span>
</div>
</form>
和.ts文件:
import { Component, .... } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({...})
export class YourFancyComponent {
myGroup: FormGroup;
constructor(private( formBuilder: FormBuilder) {
this.myGroup = this.formBuilder.group({
'ctrl1': 'defValue',
'ctrl2': 'defaultValue2'
});
}
}
对于模板驱动的表单(根据https://angular.io/guide/forms#track-control-state-and-validity-with-ngmodel,修改后的输入控件的css类从ng-pristine
更改为ng-dirty
,但这对保存按钮没有帮助。