I'm having a Reactive Form with checkboxes. Checkbox array values are getting from API. I need to default set checkbox values if array property is "isSelected": true,( Also I need to get that default value with selected value ) Could someone help one me.
This is what I tried.
getData(){
{
this.age= [
{
"ageID": 1,
"description": "0-5 years",
"isSelected": true
},
{
"ageID": 2,
"description": "5-15 years",
"isSelected": true
},
{
"ageID": 3,
"description": "15-35",
"isSelected": false
},
{
"ageID": 4,
"description": "35-60",
"isSelected": false
}
],
this.language= [
{
"languageID": 1,
"description": "Arabic",
"isSelected": false
},
{
"languageID": 2,
"description": "Chinese",
"isSelected": false,
},
{
"languageID": 3,
"description": "Hindi",
"isSelected": false,
},
{
"languageID": 4,
"description": "Tamil",
"isSelected": true,
},
{
"languageID": 5,
"description": "Japanese",
"isSelected": true,
},
]
}
}
onAgeChange(age: any, isChecked: boolean){
const ageFormArray = <FormArray>this.exampleForm.controls.ages;
if (isChecked) {
ageFormArray.push(new FormControl(age));
for(let item in ageFormArray.value){
let obj = {
"ageID": ageFormArray.value[item],
"isSelected": true,
}
console.log(obj)
}
} else {
let index = ageFormArray.controls.findIndex(x => x.value == age)
ageFormArray.removeAt(index);
}
}
onLanguageChange(language: any, isChecked: boolean){
const languageFormArray = <FormArray>this.exampleForm.controls.languages;
if (isChecked) {
languageFormArray.push(new FormControl(language));
for(let item in languageFormArray .value){
let obj = {
"ageID": languageFormArray.value[item],
"isSelected": true,
}
console.log(obj)
}
} else {
let index = languageFormArray.controls.findIndex(x => x.value == language)
languageFormArray.removeAt(index);
}
}
HTML
<div>
<h1>Reactive form</h1>
<div class="custom-control custom-checkbox" *ngFor="let data of age let j = index">
<input type="checkbox" (change)="onAgeChange( data.ageID ,$event.target.checked,$event)" name="age"> {{data.description}}<br>
</div>
<br>
<div class="custom-control custom-checkbox">
<div class="custom-control custom-checkbox" *ngFor="let data of language">
<input type="checkbox" (change)="onLanguageChange(data.description, $event.target.checked)"> {{data.description}}<br>
</div>
</div>
</div>
formControlNamedirective on the checkboxes?