1

I am using angular formbuilder to create a nested form. How do I set nested form quantity field value for each form group within updateValue() function in following code.

ngOnInit() {
   this.fastPostingForm = this.fb.group({
      Charges: this.fb.array([
        this.initCharge()
      ])
    });
}

initCharge(){
     return this.fb.group({
      room: ['', Validators.required],
      amount: ['', Validators.required],
      quantity: ['', Validators.required],
    });
 }

 UpdateValue(i) {
    this.fastPostingForm.controls.Charges[i].controls['quantity'].setValue(2); // This is not working
 }
4
  • Can you post the exact error message you are getting? Commented Oct 2, 2017 at 10:40
  • core.es5.js:1020 ERROR TypeError: Cannot read property 'controls' of undefined Commented Oct 2, 2017 at 10:42
  • You are missing one controls? this.fastPostingForm.controls.Charges.controls[i].controls['quantity'].setValue(2); Maybe consider to pass the nested group as parameter instead of index, so that you don't need to go nuts with those long paths :) Commented Oct 2, 2017 at 10:43
  • that give me following error - Property 'controls' does not exist on type 'AbstractControl'. Commented Oct 2, 2017 at 10:46

1 Answer 1

1

It should be:

(this.fastPostingForm.controls.Charges as FormArray).controls[i].controls['quantity']
                                                    .setValue(2)

or

this.fastPostingForm.get(['Charges', i, 'quantity']).setValue(2);

or

this.fastPostingForm.get(`Charges.${i}.quantity`).setValue(2);
                        ^^^
                     backtick

or you can even use patchValue method on your form:

this.fastPostingForm.patchValue({
  Charges: [...Array(i), { quantity: '2' }]
});
Sign up to request clarification or add additional context in comments.

4 Comments

Try the first one i updated it. Just copied from wrong place
first one giving me following error Property 'controls' does not exist on type 'AbstractControl'.
Try (this.fastPostingForm.controls.Charges as FormArray).controls[i].controls['quantity'].setValue(2);
AbstractControl doesn't have controls property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.