Adding formGroup in angular

  Kiến thức lập trình

I am trying to create a form in two ways. The first approach works, but the second one gives error. Here is what I’ve done:

//the first approach
  this.form = this.formBuilder.group({
     location: ['', Validators.required],
     weather: this.formBuilder.group({
       rainy: ['', Validators.required],
       sunny: ['', Validators.required]
     }),
  });
   
//the second approach
  this.form.addControl('location', new FormControl('', [Validators.required]), { emitEvent: false });
  this.form.addControl('weather', new FormGroup([]), { emitEvent: false });
   (<FormGroup>this.form.controls['weather']).addControl('rainy',
     this.formBuilder.control('', [Validators.required]), { emitEvent: false }
   );
   (<FormGroup>this.form.controls['weather']).addControl('sunny',
      this.formBuilder.control('', [Validators.required]), { emitEvent: false }
   );

When I use the second approach, the error I get is: formGroup expects a FormGroup instance. Please pass one in.
Then I found that, if I add *ngIf="form" to my form tag, this error is gone. But then I get a new error: TypeError: this.form is undefined

Does anyone know what is wrong with the second approach?

P.s. I don’t know what is the best way to call these two approaches! Is there any specific name for them, like static form declaration or dynamic, or something else?

LEAVE A COMMENT