表單值異動監聽

1 篇文章 / 0 new
author
表單值異動監聽
當需要偵測表單中任一欄位資料異動做後續相關處理時
► 訂閱事件
this.editForm = new FormGroup({
    username: new FormControl(''),
    account: new FormControl(''),
    ...
});

this.editForm.valueChanges.subscribe(data => {
    console.log('for FormGroup');
    for (var field in this.editForm.controls) {//取得所有 FromControl
        console.log(this.editForm.controls[field]);
    }
});


以 @ViewChild('registerForm') registerForm; 取得表單

this.registerForm.valueChanges.subscribe(data => {
    console.log('for NgForm');
    for (var field in this.registerForm.form.controls) {//取得所有 FormControl
        console.log(this.registerForm.form.controls[field]);
    }
});

► 表單, 主要對像
editFrom: FormGroupresisterForm: NgFrom, 看是用哪一種方式, 差異只是在取得 FormControl 時稍有差異
<form #registerForm="ngForm" [formGroup]="editForm" (ngSubmit)="onSubmit(editForm.value, editForm.valid)">
    <input type="password" placeholder="密碼" formControlName="passwd">
    <input type="password" placeholder="再次輸入" formControlName="repeatPasswd">
    ...
</form>
Free Web Hosting