簡體   English   中英

Angular 無功 forms:變化與值變化

[英]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事件只會火,一旦你blurinput字段。 此外,在這種情況下,您將獲得$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 邏輯。 有時這些表單需要值更改的“連鎖反應”才能正常工作,在這種情況下(更改)處理程序將無用

對於輸入(文本)字段,我建議根據您的用例使用changeValuesvalue

  • 如果您想實現類似於“Google 的自動完成功能”的功能,即在您鍵入時提供(搜索)建議 → 然后使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM