1 year ago

#303670

test-img

GreekSwiss

angular patchValue form Array and check the preselected checkboxes again

in one of my angular components i have a reactive form and one of the controls is a formArray, i will post some code that explains how i am adding objects into the form Array

let portfolio: Array<any> = [ here is the data ]

the user is able to choose between many accounts ( he can choose from 1 to N )

<div *ngFor="let account of portfolio.accounts; let i = index">
  <input id="a" type="checkbox" (change)="addAccount($event) [value]="account.id">
  <label for="a">{{account.name}}</label>
</div>

i am adding / removing the actual selected account with the addAccount() function

addAccount(e: any) {
const accountArray: FormArray = this.userForm.get('group1.selectedAccounts') as FormArray;
if (e.target.checked) {
    accountArray.push(new FormControl(e.target.value));
} else {
    let i: number = 0;
    accountArray.controls.forEach((item: FormControl) => {
        if(item.value == e.target.value) {
            accountArray.removeAt(i);
            return;
        }
        i++;
    });
}
}

at this point when the user has selected the accounts he wants, the accounts are in the formArray and when the form is getting submitted i execute the following code:

onSubmit(data:any) {
  let selectedAccountsArray = []
  selectedAccountsArray = data.group1.selectedAccounts
  selectedAccountsArray = this.portfolio.accounts.filter((account: any) => selectedAccountsArray.indexOf(account.positionId) != -1)
}

the onSubmit function is receiving the value of the form

the reason i am doing this is, because i have to pass at this point of time the complete Objects that the user selected and not only the account.id or account.name for example. After that my backend is doing some calculations and stuff that is not important to talk about in this thread.

After some time i am able to call via REST my backend and this will return to me the data i sent in the past and now i want to patchValue my form ( call the same reactive form like in the beggining )

The problem i am facing now is that i dont know how to patch my form at this form array and show the user the accounts he selected in the past.

The ngFor in the template will show all accounts again and i want the preselected accounts to be autoticked ( checkboxed ).

I know how to patch a formControl but patching a FormArray and also setting the checkbox is something i dont understand.

Are there any ideas or suggestions ?

angular

angular-reactive-forms

patch

formarray

0 Answers

Your Answer

Accepted video resources