I have a form with some types of inputs. There is a mistake in validation in the checkbox
type. See the stackblitz demo.
First, check the first item. Then check the second one and then uncheck the first one. It shows error message!
Html:
<form name="form" (ngSubmit)="addBookletForm.valid && addBooklet()" #addBookletForm="ngForm" novalidate >
<label *ngFor="let option of levelCheckboxes">
<div *ngIf="( booklet_level.touched || addBookletForm.submitted) && booklet_level.invalid && booklet_level.errors.required">
<div class="saz-alert saz-alert-red saz-alert-small saz-color-red" *ngIf="booklet_level.errors.required">
This is required!
</div>
</div>
<input name="booklet_level" #booklet_level="ngModel" required value="{{option.value}}" [(ngModel)]="option.checked" type="checkbox">
{{option.name}}
</label>
</form>
Typescript:
levelCheckboxes = [
{ name:'one', value:'1', checked:false },
{ name:'two', value:'2', checked:false },
{ name:'three', value:'3', checked:false }
]
I have understood your requirement. Your html can be modified as
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div *ngIf="isChecked == false">
Atleast one checkbox should be checked!
</div>
<form name="form" (ngSubmit)="addBookletForm.valid && addBooklet()" #addBookletForm="ngForm" novalidate >
<label *ngFor="let option of levelCheckboxes">
<input name="booklet_level" [(ngModel)]="option.checked" type="checkbox" (change)="isCheckBoxChecked()">
{{option.name}}
</label>
</form>
And in your .ts file you can have a function called isCheckBoxChecked() to display the respective validation error,
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
isChecked: boolean = false;
name = 'Angular';
levelCheckboxes = [
{ name:'one', value:'1', checked:false },
{ name:'two', value:'2', checked:false },
{ name:'three', value:'3', checked:false }
]
isCheckBoxChecked(){
this.isChecked = false;
this.levelCheckboxes.forEach(checkbox => {
if(checkbox.checked){
this.isChecked = true;
}
})
}
}
Hope it helps!