Patch dynamic data to repeat type in angular-formly

Discussão em 'Angular' iniciado por Melechoris, Fevereiro 12, 2025.

  1. Melechoris

    Melechoris Guest

    My goal is to patch external json data to a form which contains a FieldArrayType.

    Say I have the following formly field config:

    fields: FormlyFieldConfig[] = [
    {
    key: 'cars',
    type: 'repeat',
    fieldArray: {
    fieldGroupClassName: 'row',
    templateOptions: {
    btnText: 'Add',
    },
    fieldGroup: [
    {
    className: 'col-sm-4',
    type: 'input',
    key: 'type',
    templateOptions: {
    label: 'Type:'
    },
    },
    {
    type: 'input',
    key: 'name',
    className: 'col-sm-3',
    templateOptions: {
    label: 'Name:'
    },
    },
    ],
    },
    },
    ];


    And later on I want to patch some data to this repeat type:

    patchData() {
    let data = {
    "cars":[
    {"type":"Type1","name":"Name1"},
    {"type":"Type2","name":"Name2"}]
    };

    // Failure: Only the first car value is patched, the second car is not patched
    // (unless) 'Add' is clicked first, which is not intended.
    this.form.patchValue(data);
    }


    The problem is that at the initial load of the form, only one item is present in the repeat section. Therefore, if I patch data to the form which contains two or more items of the field array, only the first item is applied and stored in the model.

    Is there a way to programmatically add items to the FieldArray before patching the data so the data is received by the model?

    Note: The length of the data can vary.

    Please see the following stackblitz as example: https://stackblitz.com/edit/angular-vfykhx

    Continue reading...

Compartilhe esta Página