javascript - 用 AppComponent 中的 ngOnChanges 监听 FormControl 的变化?
问题描述
我正在尝试收听响应式电子邮件表单控件的更改,如下所示:
import { Component, OnChanges } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnChanges {
form: FormGroup = new FormGroup({
email: new FormControl('',[ Validators.email ])
});
get emailInput() { return this.form.get('email'); }
ngOnChanges() {
this.form.get('email').valueChanges.subscribe(val => {
const formattedMessage = `Email is ${val}.`;
console.log(formattedMessage);
});
}
}
表格如下所示:
<form [formGroup]="form">
<input placeholder="Email" type="email" formControlName="email" >
</form>
在电子邮件字段中输入时,不会记录任何内容。 这就是 Stackblitz。 想法?
更新
公认的答案是使用ngOnInitit
生命周期挂钩。我想是否应该ngAfterViewInit
只是为了确保视图完全初始化或者表单绑定总是完整的ngOnInit
?
解决方案
起初没有注意到,但您ngOnChanges
不应该在订阅可观察对象的地方。ngOnChanges
用于更改当前组件的输入参数(通常包含在 中[]
)。
像这样设置您对可观察对象的订阅,ngOnInit
您的代码将起作用:
ngOnInit() {
this.emailSubscription = this.form.get('email').valueChanges.subscribe(val => {
const formattedMessage = `Email is ${val}.`;
console.log(formattedMessage);
});
}
Angular 不会自动取消订阅,因此通常您需要保存描述的值,然后在 ngOnDestroy 中取消订阅:
ngOnDestroy() {
this.emailSubscription.unsubscribe();
}
由于您在 appComponent 中编写此代码,因此可能没有明确需要在外部执行此操作,这通常是其他所有组件的好习惯。
编辑:更新的 stackblitz显示了这个工作。
推荐阅读
- c# - 在 C# 中清除静态列表
- r - 错误:替换有 x 行,数据有 y
- qt - QML 我如何将默认选项设置为组合框的空值?
- abap - 删除一列包含字符“+”的内部表格行
- angular - 无法通过 2 个级别传递 ngModel
- android - 通过使用自定义地图提取将一个可观察的对象溢出到两个
- python - 为什么 celery beat 不安排定期任务?
- angular - 执行导出其他组件html的角度组件的正确模式
- mysql - MySQL - 计算事件之间的时间差 - LEFT JOIN、TIMEDIFF、MAX
- outlook - AppleScript - 通过按键模拟填写 Outlook 主题