Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 is not a function

Although the method is mentioned in the documentation & it is even suggested by VS Code as in this snapshot.Even VS Code is suggesting the method

My code is here:

// ... 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();
        }

What is the problem here ?

UPDATE 1:

I have created a stackblitz to show the issue

here is the link for that demo

UPDATE 2: As the error is not shown on initial loading, if you remove the this.firstStepForm.disable(); & rewrite it , you will get the error, but anyway the behavior is not correct, the form field is not disabled as expected

Also, refreshing the browser part in the stackblitz will show an error snackbar

like image 545
Ahmed Elkoussy Avatar asked Mar 05 '23 21:03

Ahmed Elkoussy


1 Answers

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

like image 74
Amit Chigadani Avatar answered Mar 09 '23 01:03

Amit Chigadani