如何使用Angular 2检查表单中的更改 [英] How to check for changes in form in Angular 2 using
问题描述
我有一个很少有数据字段和两个按钮的表单.我只想在用户对表单进行一些更改时才启用按钮.我尝试使用:
I have a form with few data fields and two buttons.I want to enable the buttons only if the user makes some changes to the form. I have tried using:
this.form.valueChanges.subscribe(data => console.log('form changes', data));
但是,当表单也加载时,最初会检测到更改.还有其他方法可以检查表单中的任何更改.我希望仅在用户对字段进行更改时才调用它,而不在表单加载时调用它.以下是我的html和打字稿代码:
But the changes are detected initially when the form loads also. Is there any other way to check for any changes in the form. I want it to be called only when user makes changes to the field and not when the form loads. Following is my html and typescript code:
profile.html:
profile.html:
<section>
<div>
<form [formGroup]="form">
<fieldset>
<div class="panel-group m-l-1 m-r-1 accordion vertical-scroll" id="">
<div class="form-group required no-gutter">
<label for="firstname"> First Name:</label>
<div class="col-md-7 col-lg-6">
<input type="text" class="form-control" id="firstname" placeholder="" name="firstname" title="firstname" formControlName="firstname" size="128" aria-required="true" maxlength="35">
</div>
</div>
</div>
</fieldset>
<div>
<button class="btn btn-primary" type="button" (click)="save()">Save</button>
<button class="btn btn-primary" type="button" (click)="cancel()">Cancel</button>
</div>
</form>
</div>
</section>
profile.component.ts:
profile.component.ts:
export class ProfileComponent implements OnInit, AfterViewInit, OnChanges {
public form: FormGroup;
constructor(private formBuilder: FormBuilder, private app: Application) {
}
loadForm(): void {
this.form = this.formBuilder.group({
firstname: [this.app.firstName, Validators.required]
});
this.form.valueChanges.subscribe(data => console.log('form changes', data));
}
save(): void {
}
cancel(): void {
};
ngOnInit() {
this.loadForm();
}
ngAfterViewInit() {
this.loadForm();
}
}
推荐答案
您可以使用.dirty
(或.pristine
)值来确定用户是否使用UI来更改控件值:
You can use the .dirty
(or .pristine
) values to determine if a user has used the UI to change the control value:
<button class="btn btn-primary" type="button" (click)="save()" [disabled]="!form.dirty" >Save</button>
<button class="btn btn-primary" type="button" [disabled]="!form.dirty"(click)="cancel()">Cancel</button>
https://angular.io/docs/ts/latest/api/forms/index/AbstractControl-class.html#!#dirty-anchor
dirty:布尔值如果用户更改了值,则控件为脏 在用户界面中.
dirty : boolean A control is dirty if the user has changed the value in the UI.
请注意,以编程方式更改控件的值不会标记它 肮脏的.
Note that programmatic changes to a control's value will not mark it dirty.
touched:boolean一旦用户拥有一个控件,就将其标记为触摸 触发了模糊事件.
touched : boolean A control is marked touched once the user has triggered a blur event on it.
这篇关于如何使用Angular 2检查表单中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!