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

前端 未结 2 1276
小鲜肉
小鲜肉 2021-01-19 11:17

When I try to use the disable method on a formGroup in my Angular 6 app , I get this error in the browser console :

TypeError: this.personForm.disable

相关标签:
2条回答
  • 2021-01-19 11:49

    The form object that you have created using template driven approach is of type NgForm and not FormGroup

    There is a form attribute inside ngForm object which is actually of type FormGroup.

    So you should be doing

    this.personForm.form.disable()
    

    EDIT :

    You have to move your code to AfterViewChecked life cycle hook event, since your formGroup wont be ready ngAfterViewChecked() is triggered.

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

    And also postpone the change detection to avoid expression changed error using ChangeDetectorRef.

    DEMO

    0 讨论(0)
  • 2021-01-19 12:12

    I have discovered the reason for this error:

    This form is made in the html template using ngForm, then I used ViewChild to get hold of the form in the typescript file, I noticed that I made that object of type FormGroup but ngForm is different than FormGroup (in my use cases it wasn't clear) that is why the FormGroup disable method is not working on the ngForm

    Note:

    (VS code is suggesting it as my type for that variable is FormGroup which is misleading the editor to give me that suggestion)

    Thanks for everyone who tried to help.

    Update:

    In case someone is reluctant to depend on detectChanges() like me & Building upon the excellent Answer of Amit , we can disable the NgForm in this AfterContentChecked to avoid using 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

    0 讨论(0)
提交回复
热议问题