sridharan
sridharan

Reputation: 2065

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")
}

Upvotes: 0

Views: 1248

Answers (3)

Poul Kruijt
Poul Kruijt

Reputation: 71961

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 :)

Upvotes: 1

Srikar Phani Kumar M
Srikar Phani Kumar M

Reputation: 1384

There are 4 different ways to do this: You can use any one of the following:

1) this.setUpForm.get(['MorningSpan', 'StartTime']).setValue("24:00")

2) this.setUpForm.get('MorningSpan').get('StartTime').setValue("24:00")

3) this.setUpForm.controls['MorningSpan'].controls['StartTime'].setValue("24:00")

4) this.setUpForm.controls.MorningSpan.controls.StartTime.setValue("24:00")

Upvotes: 1

Gabriel Sereno
Gabriel Sereno

Reputation: 855

Your problem is because you're using [] instead of (). Try it: this.setUpForm.get('MorningSpan.StartTime').setValue("24:00")

Upvotes: 2

Related Questions