Angular 6 FormGroup.disable() 方法不适用于我的模板驱动的 NgForm

Angular 6 FormGroup.disable() method is not working with my template driven NgForm

当我尝试在我的 Angular 6 应用程序的 formGroup 上使用禁用方法时,我在浏览器控制台中收到此错误:

TypeError: this.personForm.disable is not a function

虽然方法是[​​=15=]

我的代码在这里:

// ... many parts skipped, the form here is template driven 
// but still personForm is a FormGroup , 
// I am trying to disable the whole FormGroup with all child elements
@ViewChild('personForm') personForm: FormGroup;

        if (true) {
       // if I console.log here the form, I can see it is created already
         console.log(this.personForm);              
// output of console.log is 
// NgForm {submitted: false, _directives: Array(0), ngSubmit: EventEmitter, form: FormGroup}

         this.personForm.disable();
        }

这里有什么问题?

更新 1:

我创建了一个 stackblitz 来展示这个问题

here is the link for that demo

更新 2: 由于错误未在初始加载时显示,如果您删除 this.firstStepForm.disable(); 并重写它,您将收到错误,但无论如何行为不正确,表单字段未按预期禁用

此外,在 stackblitz 中刷新浏览器部分会显示错误 snackbar

您使用模板驱动方法创建的表单对象是 NgForm 类型而不是 FormGroup

ngForm 对象中有一个 form 属性,实际上是 FormGroup.

类型

所以你应该这样做

this.personForm.form.disable()

编辑:

您必须将您的代码移动到 AfterViewChecked 生命周期挂钩事件,因为您的 formGroup 不会就绪 ngAfterViewChecked() 被触发。

ngAfterViewChecked() {
      console.log(this.personForm.form);    
      this.personForm.form.disable(); 
      this.cdr.detectChanges();  
} 

并且还推迟更改检测以避免使用 ChangeDetectorRef 的表达式更改错误。

DEMO

我发现了这个错误的原因:

此表单是使用 ngForm 在 html 模板中制作的,然后 我使用 ViewChild 在打字稿文件中获取表单,我注意到我创建了 FormGroup 类型的对象,但是 ngForm 与 FormGroup 不同(在我的用例中不清楚),这就是为什么 FormGroup 禁用方法不适用于 ngForm

注:

(VS 代码建议它,因为我对该变量的类型是 FormGroup,这会误导编辑给我该建议)

感谢所有试图提供帮助的人。

更新:

以防有人像我一样不愿意依赖 detectChanges() &基于 Amit 的优秀答案,我们可以在此 AfterContentChecked 中禁用 NgForm 以避免使用 detectChanges()

  // instead of disabling here & using cdr.detectChanges()

  // ngAfterViewChecked() {
  //     console.log(this.personForm.form);    
  //     this.personForm.form.disable(); 
  //     this.cdr.detectChanges();  
  // } 

  // we can put our disable here
  ngAfterContentChecked() {
    this.personForm.form.disable();
  }

Stackblitz demo