[英]Angular Reactive forms : change vs valueChanges
我在 Angular 7 中使用反應式forms。
我有許多依賴於其他領域的領域。
我對我應該使用什么(change)
或this.form.get("control_name").valueChanges
感到好奇?
例如。 如果兩者都適用於輸入,那么我想知道它們之間的區別、優缺點。
哪個性能更好?
讓我們考慮一下您正在尋找的是監聽type="text"
input
標簽的變化
valueChanges
情況下由於它是一個 Observable,它將以一個新值觸發。 該值將是input
字段的更改值。 要收聽它,您必須subscribe
valueChanges
Observable。 像這樣的東西:
this.form1.controls['name'].valueChanges.subscribe(change => {
console.log(change); // Value inside the input field as soon as it changes
});
(change)
事件的情況下在的情況下change
情況下,對於input
標簽,則change
事件只會火,一旦你blur
從遠input
字段。 此外,在這種情況下,您將獲得$event
對象。 從那個$event
對象中,您必須提取字段值。
所以在代碼中,這看起來像這樣:
import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({...})
export class AppComponent {
name = 'Angular';
form1: FormGroup;
form2: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form1 = this.fb.group({
name: [],
email: []
});
this.form2 = this.fb.group({
name: [],
email: []
});
this.form1.controls['name'].valueChanges.subscribe(change => {
console.log(change);
});
}
onForm2NameChange({ target }) {
console.log(target.value);
}
}
在模板中:
<form [formGroup]="form1">
<input type="text" formControlName="name">
<input type="text" formControlName="email">
</form>
<hr>
<form [formGroup]="form2">
<input type="text" formControlName="name" (change)="onForm2NameChange($event)">
<input type="text" formControlName="email">
</form>
這是供您參考的工作示例 StackBlitz 。
注意:這完全取決於您的用例,哪一個更合適。
對於您的特定用例,我建議使用 RxJS Operators 來完成工作。 像這樣的東西:
zipCodeFormControl
.valueChanges
.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap(
zipcode => getAddressFromZipcode(zipcode)
),
map(res => res.actualResult)
)
.subscribe(addressComponents => {
// Here you can extract the specific Address Components
// that you want to auto fill in your form and call the patchValue method on your form or the controls individually
});
這是個案,但我發現復選框和單選按鈕(真/假類型控件)之類的東西與(更改)處理程序一起使用效果更好,輸入和文本字段通常更適合 valueChanges。
盡管我不確定性能,但我認為這將是處理此決定時的理想用例。
valueChanges 的一個很好的用例(對於一切)是一個復雜的形式,有很多 ngIf 邏輯。 有時這些表單需要值更改的“連鎖反應”才能正常工作,在這種情況下(更改)處理程序將無用
對於輸入(文本)字段,我建議根據您的用例使用changeValues
或value
:
changeValues
。change
。然而,這只是一個經驗法則,魔鬼在細節中。
這是我在進行自己的研究/測試時編寫的一個工作示例的代碼,為了比較,它實現了兩種方法:
我建議僅使用反應式 Forms 邏輯。 如果您需要具有(change)
之類的行為,以便僅在執行 blur 時發出該值,您可以像這樣設置updateOn: 'blur'
:
this.fb.group({
title: this.fb.control('', { updateOn: 'blur' }),
description: '',
})
或者對整個表格這樣:
this.fb.group({
title: '',
description: '',
},{updateOn: 'blur'})
現在您可以訂閱 valueChanges:
this.form.valueChanges.subscribe(change=>{ console.log(change) })
這將記錄每次您輸入內容時的描述更改,並且僅在考慮第一個示例時離開輸入字段時記錄標題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.