Ank*_*iya 0 angular angular-reactive-forms angular-observable angular-forms
我在Angular 7中使用反应形式。
我有很多字段都依赖于其他字段。
我很好奇我应该使用(change)或this.form.get("control_name").valueChanges?
对于前。两者都将在输入上起作用。我想知道它们之间的优缺点。
哪个效果更好?
让我们考虑一下,您正在寻找的是听input标签上的更改type="text"
valueChanges由于它是一个Observable,它将使用新值触发。该值将是该input字段的更改值。而且听它,你将不得不subscribe在valueChanges观察的。像这样:
this.form1.controls['name'].valueChanges.subscribe(change => {
console.log(change); // Value inside the input field as soon as it changes
});
Run Code Online (Sandbox Code Playgroud)
(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);
}
}
Run Code Online (Sandbox Code Playgroud)
并在模板中:
<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>
Run Code Online (Sandbox Code Playgroud)
这是供您参考的工作样本StackBlitz。
注意:这完全取决于您的用例,哪种情况更合适。
对于您的特定用例,我建议使用RxJS运算符来完成工作。像这样:
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
});
Run Code Online (Sandbox Code Playgroud)
我建议仅使用反应式表单逻辑。如果你需要有像has这样的行为(change),以便只有在执行blur时才发出该值,你可以updateOn: 'blur'这样设置:
this.fb.group({
title: this.fb.control('', { updateOn: 'blur' }),
description: '',
})
Run Code Online (Sandbox Code Playgroud)
或者像这样的整个表格:
this.fb.group({
title: '',
description: '',
},{updateOn: 'blur'})
Run Code Online (Sandbox Code Playgroud)
现在您可以订阅 valueChanges:
this.form.valueChanges.subscribe(change=>{ console.log(change) })
Run Code Online (Sandbox Code Playgroud)
在第一个示例中,这将在您每次键入内容时记录描述中的更改,并且仅在离开输入字段时记录标题的更改。
| 归档时间: |
|
| 查看次数: |
4340 次 |
| 最近记录: |