I'm currently learning Angular 6 and I have a requirement to mark checkboxes based on specific IDs from two arrays:
this.skillArray = [
{ID: 1, name: "Diving"},
{ID: 2, name: "Firefighting"},
{ID: 3, name: "Treatment"},
{ID: 4, name: "Mechanics"},
{ID: 5, name: "Floods"},
{ID: 6, name: "Drilling"},
{ID: 7, name: "Electricity"},
{ID: 8, name: "Celebrations"},
{ID: 9, name: "Events"},
{ID: 10, name: "Prayer"}
]
var splitstr = ["9", "7"];
My goal is to check the checkbox for IDs 9 & 7. I managed to accomplish this and also implemented an onchange function to post the value. However, the issue I encountered was that the checked values were not getting pushed to the array. How can I resolve this?
<form [formGroup]="myForm">
<div *ngFor="let data of skillsArray">
<p><input type="checkbox" [checked]="inputChecked(data.ID)" (change)="onChange(data.ID, $event.target.checked)"> {{data.name}}</p>
</div>
</form>
inputChecked(id:any) {
let checked = false;
console.log(this.splitstr);
for (let l = 0; l <this.splitstr.length; l++) {
let temp = this.splitstr[l];
if (temp == id) {
checked = true;
}
}
return checked;
}
onChange(value: any, isChecked: boolean) {
const skillFormArray = <FormArray>this.myForm.controls.VFields;
if (isChecked) {
skillFormArray.push(new FormControl(value));
}
else
{
let index = skillFormArray.controls.findIndex(x => x.value == value)
skillFormArray.removeAt(index);
}
}