访问 ngAfterViewInit 内的表单控件

Hal*_*lil 4 angular

我想访问表单控件并有条件地禁用某些控件。在以下代码中,表单没有控件:

Component

export class OfferDialogComponent implements OnInit, AfterViewInit {

    freemium = false;
    @ViewChild('editForm') editForm: NgForm;

    ngAfterViewInit(): void {
        this.editForm.form.get("trialPeriod").disable();
    }
}
Run Code Online (Sandbox Code Playgroud)

Template

<form name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm">
Run Code Online (Sandbox Code Playgroud)

如何有条件地访问和初始化表单控件?

Vik*_*kas 5

来自 Angular 文档

模板驱动的表单将其表单控件的创建委托给指令。为了避免检查错误后发生更改,这些指令需要多个周期来构建整个控制树。这意味着您必须等到下一个更改检测周期发生才能从组件类中操作任何控件。

例如,如果您使用@ViewChild(NgForm) 查询注入表单控件并在生命周期挂钩中检查它ngAfterViewInit,您会发现它没有子级。您必须先触发更改检测周期,setTimeout()然后才能从控件中提取值、测试其有效性或将其设置为新值。

修改后的代码:

ngAfterViewInit(): void {
  setTimeOut(() => {
    this.editForm.form.get('trialPeriod').disable();
  });
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用 ngAfterViewChecked

import { Component, ViewChild, ChangeDetectorRef } from '@angular/core';
class App {
  constructor(private cdRef: ChangeDetectorRef) {}
  ngAfterViewChecked() {
    if (this.editForm.controls.name) this.editForm.form.get('name').disable();

    this.cdRef.detectChanges(); 
//Forcing change detection to avoid ExpressionChangedAfterItHasBeenCheckedError
  }
}
Run Code Online (Sandbox Code Playgroud)