Ram Guiao
Ram Guiao

Reputation: 362

How to set initial value to a FormArray control in Ionic 2?

I am trying to add an initial value to a FormArray control. I am using this code:

    if(this.navParams.get('kids').length > 1) {
        for(let i=0; i<this.navParams.get('kids').length - 1; i++) {
            this.addChild();
        }
        for(let i=0; i<this.navParams.get('kids').length; i++) {
            this.registrationForm.controls['child'][i]['child_first_name'].setValue("asdasdasd");
        }
    }

However, I think I am using setValue method in a wrong way. I am having this error:

Error

Here is the code for addChild:

addChild() {
    // add child to the list
    const control = <FormArray>this.registrationForm.controls['child'];
    control.push(this.initChild());
    // console.log(this.registrationForm.value);
}

Here is the initChild Method:

initChild() {
    // initialize child form
    return this.formBuilder.group({
        child_first_name: ['', Validators.compose([Validators.maxLength(255), Validators.required])],
        child_last_name: ['', Validators.compose([Validators.maxLength(255), Validators.required])],
        child_gender: ['', Validators.compose([Validators.required])],
        child_bdate: ['', Validators.compose([Validators.required])]
    });
}

I am finding a solution for like almost 2 days. This is my first time to use Ionic. Any help would be appreciated. Thanks, SO community!

Upvotes: 0

Views: 562

Answers (1)

yurzui
yurzui

Reputation: 214315

Simple way of doing that is using get method like:

this.registrationForm.get(['child', i, 'child_first_name']).setValue('asdasdasd');

If you use controls property then it should look as follows:

((this.registrationForm.controls['child'] as FormArray).controls[i] as FormGroup).controls['child_first_name'].setValue("asdasdasd");

one more alternative could look like:

this.registrationForm.patchValue({
  child: [...Array(i), { child_first_name: 'asdasdasd' }]
});

Stackblitz Example

Upvotes: 1

Related Questions