dhruvkumar rathod
dhruvkumar rathod

Reputation: 39

Cant use formGroup.controls['xxx'].setValue('someString');

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

Answers (4)

dhruvkumar rathod
dhruvkumar rathod

Reputation: 39

This works for me

  (((<FormArray>this.addUserForm.controls['roleFormArray']).at(someIndex)) as FormGroup).controls['role'].setValue('somestring');

Upvotes: 1

igor_c
igor_c

Reputation: 1250

Try

this.roleFormArray.setValue({
    role: 'value',
    node: 'value',
});

Upvotes: 0

Sumit Vekariya
Sumit Vekariya

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

Ansuman
Ansuman

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

Related Questions