首页 > 解决方案 > 用 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

标签: javascriptangulartypescriptrxjs

解决方案


起初没有注意到,但您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显示了这个工作。


推荐阅读