让我们考虑一下,您正在寻找的是在 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>
这里有一个Working Sample 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
});