i have an angular4 form which is built using form builder. The code is as follows.
initializeFromControls() {
let obj = {
firstname: new FormControl('', ),
lastname: new FormControl('', ),
email: new FormControl('',
[Validators.required,
Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")]),
status: new FormControl('', ),
role_id: new FormControl(''),
account_ids: this.formBuilder.array([])
}
this.userFrm = this.formBuilder.group(obj);
}
Now i have another field named account_ids which is an array. The account ids are fetched from the getAccounts api call.
ngOnInit() {
this.initializeFromControls();
this.getAccounts();
}
Selected Account ids are send to backend using the following code.
onChange(account_id:string, isChecked: boolean) {
const accountIdArray = <FormArray>this.userFrm.controls.account_ids;
if(isChecked) {
accountIdArray.push(new FormControl(account_id));
} else {
let index = accountIdArray.controls.findIndex(x => x.value == account_id)
accountIdArray.removeAt(index);
}
console.log(this.userFrm.getRawValue());
}
Now I need to pre-populate account ids (formArray) on edit page.
The template is as follows.
<div *ngFor="let account of accounts">
<input type="checkbox" (change)="onChange(account.id, $event.target.checked)">{{account.id}} {{account.acc_name}}<br>
</div>
Any idea on how to achieve this?