I have defined a FormGroup inside a FormArray. I am setting a value in a specific FormControl. But when I set the value using setValue
method in a specific control, that value is duplicated in other controls in the same formGroup.
this.listItemForm = this.formbuilder.array([]);
let fromGroup_ = formbuilder.group({
'8c159f74-b4208eae_image1_page1_1': [''],
'8c159f74-b4208eae_image2_page1_1': ['']
});
this.listItemForm.push(fromGroup_);
let formGroup:FormGroup = listItemForm.at(0) as FormGroup;
if(formGroup.get('8c159f74-b4208eae_image1_page1_1')){
formGroup.get('8c159f74-b4208eae_image1_page1_1').setValue('new value added');
}
console.log(formGroup.value);
OUTPUT
Expected
{
8c159f74-b4208eae_image1_page1_1: 'new value added',
8c159f74-b4208eae_image2_page1_1: ''
}
Actual output
{
8c159f74-b4208eae_image1_page1_1: 'new value added',
8c159f74-b4208eae_image2_page1_1: 'new value added'
}
I am using Angular version 7. Not sure why it is duplicating. Any thoughts?
Also please note, I have this above formArray inside a formgroup. This is added just to explain the question. I know this works when I tried the above alone.
UPDATE
Those form controls were added dynamically. Therefore somehow all the formcontrols have same reference. Therefore the issue. I have found out.
Thanks for who all tried help!
CodePudding user response:
A FormGroup
has properties of type [key: string]: AbstractControl
.
let fromGroup_ = new FormGroup({
'8c159f74-b4208eae_image1_page1_1': new FormControl(''),
'8c159f74-b4208eae_image2_page1_1': new FormControl(''),
});
I'm not sure why tsc even lets you compile that code to be honest, maybe the type definition differs in Angular 7?
CodePudding user response:
Do something like this
Use FormControl
while defining values for FormGroup
this.listItemForm = new FormArray([]);
let fromGroup_: any = new FormGroup({
'8c159f74-b4208eae_image1_page1_1': new FormControl(''),
'8c159f74-b4208eae_image2_page1_1': new FormControl(''),
});
this.listItemForm.push(fromGroup_);
let formGroup: FormGroup = this.listItemForm.at(0) as FormGroup;
if (formGroup.get('8c159f74-b4208eae_image1_page1_1')) {
formGroup
.get('8c159f74-b4208eae_image1_page1_1')
.setValue('new value added');
}
console.log(formGroup.value);
Stackblitz: https://stackblitz.com/edit/angular-7-reactive-form-validation-xmswmj