How can I do the validation of checking that at least 1 checkbox is selected from a checkbox list in Angular 2 template forms?
HTML code.
<div class="form-control" style="max-height: 300px; overflow: auto">
<div *ngFor="let item of items" class="checkbox">
<label for="{{item.id}}">
<input type="checkbox" value="{{item.id}}" required id="{{item.id}}" [(ngModel)]="item.isSelected" />
<span class="text-body">{{item.name}}</span>
</label>
</div>
</div>
<div *ngIf="!isAtleastOneItemSelected()" class="alert alert-error">
Select at least one item
</div>
Component Code.
public isAtleastOneItemSelected() {
const selectedItems = this.items.filter((item) => item.isSelected);
if (selectedItems.length > 0) {
return true;
} else {
return false;
}
}
I have already checked the Reactive form way of doing this here. So, wanted to check how we can do this in Template Forms. Using the code that I have pasted above, things are working fine but on page load the error message is showing up as there is no check for dirty or touched there. I was stuck with this issue.
Any help on this would be appreciated.
Thanks.