I'm trying to set default value as checked on a checkbox inside my ngFor. This is my array of checkbox items:
tags = [{
name: 'Empathetic',
checked: false
}, {
name: 'Smart money',
checked: true
}, {
name: 'Minimal help after writing check',
checked: false
}, {
name: 'Easy term sheet',
checked: true
}];
This is my html
<div class="form-group">
<div class="form-check" *ngFor="let tag of tags;">
<label class="form-check-label" for="tag{{tag.value}}">
<input
class="form-check-input"
type="checkbox"
id="tag{{tag.value}}"
name="tagOptions"
[(ngModel)]="tag.checked">
{{tag.name}}
</label>
</div>
</div>
The desired result is to get 2 checked, and 2 unchecked boxes, but all of them are unchecked. I've also tried different variations with [checked]="tag.checked", but it didn't seem to do the trick.
This solved my problem with the checked/unchecked checkboxes, while I still had control over changes in my variables.
HTML
<div class="form-group">
<div class="form-check" *ngFor="let tag of tags; let i = index;">
<label class="form-check-label" for="tag{{tag.value}}">
<input
class="form-check-input"
type="checkbox"
id="tag{{tag.value}}"
name="tagOptions"
(change)="changeCheckbox(i)"
[checked]="tag.checked">
{{tag.name}}
</label>
</div>
.ts
changeCheckbox(tags, i) {
if (tags) {
this.tags[i].checked = !this.tags[i].checked;
}
}
Use the checked property instead of ngModel,
<div class="form-group">
<div class="form-check" *ngFor="let tag of tags">
<label class="form-check-label" for="tag{{tag.value}}">
<input
class="form-check-input"
type="checkbox"
id="tag{{tag.value}}"
name="tagOptions"
[checked]="tag.checked">
{{tag.name}}
</label>
</div>
</div>
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With