Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

patch Value in a nested form control using angular2

I need to set a value in a nested control in a FormBuiler and the model is the following:

this.addAccForm = this.fb.group({
      accid: ['', Validators.required],
      status: '',
      cyc: this.fb.array([
        this.initCyc(),
      ])
    })

initCyc() {
      return this.fb.group({
        cycid: ['', Validators.required],
        name: ['', Validators.required],
        description: ['', Validators.required],
        status: ['', Validators.required],
        det: this.fb.group({
            dcycid: ['', Validators.required],
            status: ['', Validators.required]
        })
      })

I need to set a value cycid and also dcycid but I m stuck to it, I've tried to use the following line , but it does NOT help :

this.addAccForm.patchValue({cyc: { [0]: {cycid: 1234567 }}});

//

this.addAccForm.patchValue({cyc: { [0]: { det : {dcycid: 9876543}}}});

Any idea how it should be?

like image 256
K Oul Avatar asked Jun 02 '17 06:06

K Oul


3 Answers

This did the trick for me:

this.addAccForm.patchValue({'cyc': {cycid: 1234567 }});
like image 159
Alexandre Avatar answered Sep 22 '22 23:09

Alexandre


Try with theese codes

this.addAccForm.patchValue({cyc: {cycid: 1234567 }});

this.addAccForm.patchValue({cyc: { det : {dcycid: 9876543}}});

Another solution is:

(< FormGroup >this.addAccForm.controls['cyc']).controls['cycid'].patchValue('1234567');
(< FormGroup >this.addAccForm.controls['cyc']).controls['det'].controls['dcycid'].patchValue('1234567');
like image 20
sainu Avatar answered Sep 23 '22 23:09

sainu


Update

Updating nested fields of an Angular FormGroup looks cleaner using the get method, like this:

this.addAccForm.get('cyc.det.dcycid').patchValue(9876543);

And if for some reason you like the object syntax:

this.addAccForm.get('cyc.det').patchValue({ dcycid: 9876543 });
like image 34
zzantares Avatar answered Sep 22 '22 23:09

zzantares