Skip to content
Advertisement

TypeError: Cannot read property ‘setValue’ of undefined multiple form group

I am using multiple formgroup particular values I need to change data values before submit. but get error TypeError: Cannot read property ‘setValue’

    this.setUpForm = this.formBuilder.group({
          MorningSpan: this.formBuilder.group({
            StartTime: ['00:00'],
            EndTime: ['11:59'],
          }),
        });
    onSubmit(){
      this.setUpForm.get['MorningSpan.StartTime'].setValue("24:00")
}

Advertisement

Answer

There are multiple ways, but I guess you are looking for this:

onSubmit(){
  this.setUpForm.get(['MorningSpan', 'StartTime']).setValue('24:00');
}

You basically pass in a path array

Another way would be to call get twice, but that can get iffy with a deep path:

onSubmit(){
  this.setUpForm.get('MorningSpan').get('StartTime').setValue('24:00');
}

And of course you can use the dot limited path as well:

onSubmit(){
  this.setUpForm.get('MorningSpan.StartTime').setValue("24:00");
}

But personal opinion wise, I like the array approach better, because it gives you the ability (if you are into these kind of things) to make it completely type safe for your form. You will need to write some extra code though, but it will also make refactoring easier. Something to keep in mind 🙂

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement