监听 Angular 10 中的模板驱动表单更改

Listen for template driven form changes in Angular 10

我的 angular 10 应用程序中有一个模板驱动的表单,我正在尝试监听它的更改,以便我可以向用户显示 'changed, please submit updates' 消息。

HTML

<form (ngSubmit)="submit()" class="form-horizontal" #opportunityForm="ngForm">
...

opportunity.component.ts

export class OpportunityComponent implements OnInit {

  @ViewChild('opportunityForm') ngForm: NgForm;

  ngOnInit(): void {
    ...
    this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(x => {
      console.log(x);
    })

但出现错误:

TypeError: Cannot read property 'form' of undefined

因为 ngForm 没有初始化。这是一个类似的问题: which has a running answer at https://ng-run.com/edit/CGoUiw88N7OmI7x0YmHJ 有同样的问题。

如何在监听更改之前抓取表单并确保它存在?我正在使用 Angular 10.2.0

不确定这是否会有所不同,但整个页面都包裹在

<div *ngIf="loaded">

在 ngOnInit

中调用 api 后设置
ngOnInit(): void {
  this.dataService.getOpportunity(this.id)
        .subscribe(data => {
           ...  //fills the data up
        }, error => console.error(error),
        () => {
            console.log(this.loaded);
            console.log(this.ngForm);
        });

输出 true(对于已加载)和 undefined(对于 this.ngForm)。

更新*

所以它看起来确实是因为我只有在数据返回后才加载整个表单。因为它不在页面上,所以 @ViewChild 可以挂钩它。我将我的 *ngIf 放在表单内的 div 上,它工作正常

尝试向 @ViewChild 装饰器添加 static: true 选项:

@ViewChild('opportunityForm', { static: true }) ngForm: NgForm;

Ng-run Example

否则您必须将订阅移至 ngAfterViewInit 挂钩