【问题标题】:Listen for template driven form changes in Angular 10在 Angular 10 中监听模板驱动的表单更改
【发布时间】:2021-02-18 03:29:00
【问题描述】:

我的 Angular 10 应用程序中有一个模板驱动的表单,我正在尝试监听更改,以便向用户显示“已更改,请提交更新”消息。

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 没有初始化。这是一个类似的问题:how to listen of angular template driven form changeshttps://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 上,它工作正常

【问题讨论】:

    标签: angular angular-template-form


    【解决方案1】:

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

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

    Ng-run Example

    否则你必须将订阅移动到ngAfterViewInit hook

    【讨论】:

    • 我添加了更新的 ng-run 示例。如果它仍然不适合您,那么您有一些带有 *ngIf 的包装器,并且可以使用 setter for ViewChild 就像这里 ng-run.com/edit/O2yXbflec2xvl6lkPQJ2
    • 谢谢。我在 stackblitz 中设置的所有演示都按预期工作。一定和我的配置有关
    猜你喜欢
    • 1970-01-01
    • 2017-01-30
    • 2016-04-26
    • 2022-01-23
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多