Search code examples
angulartreeformbuilderangular-formbuilder

setPath() to add FormGroup in FormArray not work


i built an orgChart using tree Object and FormGroup. As you can see, i've nodes associated each one.

var treen = [{
 name:"name",
 cargo:"cargo",
 subordinados:[{
   name:"name 2",
   cargo:"cargo 2",
   subordinados: []
 }]
}];

Each "subordinados" is an FormArray.

when i use formGroup.setPath() to do add new index in "subordinados" as FormGroup type, seems it does not work. and the formGroup still the same.

follow the method i to do it:

    clicou( f: FormControl)
{
    const arrColaborador = new FormArray([]);

    const sub = this.builder.group({
        nome: new FormControl('teste'),
        cargo: new FormControl('teste'),
        subordinados: arrColaborador
    });

    f.patchValue({
        subordinados: [sub]
    })

    console.log(f);
}

how can i do that and make the formArray sting changed by the method ?


Solution

  • I found answer following a https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/

    as you see, i've used var subordinados = f.get('subordinados') as FormArray; to get formArray and so, i use subordinados.push() to add a new index.

    this way works with me.