[英]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.