Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Insert value in formgroup reactive forms

I have something like this

let formGroup = new FormGroup({
  operationalAM: new FormGroup({
    endTime: new FormControl('')
  }),
  operationalPM: new FormGroup({
    startTime: new FormControl('')
  })
});

I am trying to set value to endTime and startTime like this

formGroup.controls.operationalAM.value.endTime.setValue('1300');
formGroup.controls.operationalPM.value.startTime.setValue('');

But I am having error

TypeError: formGroup.controls.operationalAM.value.endTime.setValue is not a function

Does anybody knows hwo to set value to formGroup inside formGroup?

Upvotes: 2

Views: 2812

Answers (4)

MH Mazen
MH Mazen

Reputation: 101

you can also use the patchValue Method as follows:

 formGroup.patchValue({
 operationalAM: ({
 endTime:'1'
 }),
operationalPM:({
 startTime:'2'
})
});

you don't need to specify all fields here only the ones you need
source: this Question

Upvotes: 0

Birhan Nega
Birhan Nega

Reputation: 681

Since you have formGroup inside another formGroup, You should have to refer controls inside the inner formGroup

formGroup.controls.get('operationalAM.startTime').setValue('1300');
formGroup.controls.get('operationalPM.endTime').setValue('');

The second way is to use getter

like

 get startTime(){
  return this.yourform.get('operationalAM.startTime')
 }
 get endTime(){
  return this.yourform.get('operationalPM.endtime')
 }

This returns controls then you can set value for the controls like

this.yourform.get('endtime').setValue(value);

Upvotes: 0

Athanasios Kataras
Athanasios Kataras

Reputation: 26450

You set values in controls like this:

formGroup.controls.get('operationalAM').setValue({ endTime: '1300' });
formGroup.controls.get('operationalPM').setValue({ startTime: '1300' });

You can use the patchValue which works like:

Use the patchValue() method to replace any properties defined in the object that have changed in the form model.

formGroup.controls.get('operationalAM').patchValue({ endTime: '1300' });

This way you keep the reference but update only the value of endTime

Upvotes: 4

Andrei
Andrei

Reputation: 12206

it should be

formGroup.controls.operationalAM.controls.endTime.setValue('1300');
formGroup.controls.operationalPM.controls.startTime.setValue('');

Upvotes: 2

Related Questions