Reputation: 39
Cant use FormGroup.controls['lable'].setValue('some string');
My Angular reactive form have FormControls and a FormArray. In method I want to set value at some index of FormArray. I can able to get FormArray and FormGroup at specific Index (b is foormGroup at some index in code). but after i am unable to set value to that FormGroup.
FORM DECLARATION (WORKING)
this.addUserForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
primaryNode: [{lable: '' , uuid: ''},Validators.required],
email: ['', Validators.required],
roleFormArray: this.formBuilder.array([]),
password: ['', Validators.required],
repeatPassword: ['', Validators.required]
});
ADD FORM IN FORMARRAY(WORKING)
roleFormArray.push(this.formBuilder.group({
role: ['', Validators.required],
node: [{lable: '' , uuid: ''}, Validators.required]
}));
let a = this.addUserForm.get('roleFormArray');
NOT WORKING CODE
In method
let b = (<FormGroup((<FormArray>this.addUserForm.controls['roleFormArray']).controls[index]));
debugger //till now b have data as FormGroup
//but this line is not working
b.controls['role'].setValue('somevalue');
I want to set value to 'role' and 'node'
Upvotes: 1
Views: 624
Reputation: 39
This works for me
(((<FormArray>this.addUserForm.controls['roleFormArray']).at(someIndex)) as FormGroup).controls['role'].setValue('somestring');
Upvotes: 1
Reputation: 1250
Try
this.roleFormArray.setValue({
role: 'value',
node: 'value',
});
Upvotes: 0
Reputation: 488
Like I mentioned in the comment, You can specify the index of the formgroup inside the formarray and access the formcontrols of that formgroup:
b.at(index).controls['role'].setValue('somevalue');
Upvotes: 0
Reputation: 1494
As it's a formArray, you could try:
b.controls[index].controls['role'].setValue('somevalue');
or:
b.get([index, 'role']).setValue('somevalue');
Upvotes: 1