0

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, I get two errors:

  1. TypeError: this.form is undefined
  2. formGroup expects a FormGroup instance. Please pass one in.

Then I found that, if I add *ngIf="form" to my form tag, the second error is gone but not the first one.

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?

1

1 Answer 1

0

You need to define form first:

form = new FormGroup({});

Because of type safety, what you really need is FormRecord (or UntypedFormGroup).

Sign up to request clarification or add additional context in comments.

3 Comments

Form has been defined already (form!: FormGroup), to shorten the question I didn't add it and just used this.form.
That doesn't mean it's defined. form has FormGroup type, but it's not assigned to any value, so its value is undefined. Exclamation mark doesn't help here either.
You can't just write x!: number and then this.x++ without assertion to value first.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.