If no checkbox is selected I want to show error message. and hide error message when its checked. it is showing initially, when I deselect its not showing error message.Appreciate your help greatly. Thank you.
Here is my html code for three forms.
<div *ngIf="submitted && fc.cb.errors" >
<p *ngIf="fc.cb.errors.required" >
Please select atleast one policy
</p>
</div>
</div>
<div *ngFor="let product of templateParamterTypes['cluster_network_policy']">
<label >
<input
type="checkbox" [value]="true" formControlName="cb" [(ngModel)]="product.isChecked"
(change)="changeSelection(product.id)" /> {{ product.template_name }}
<span >
<span ></span>
</span>
</label>
</div>
ts:
this.clusterForm = this.formBuilder.group({
securityForm: this.formBuilder.group({
clusternames: [null, Validators.required],
label: [null, [Validators.required,Validators.pattern(/^[a-zA-Z0-9] $/)]],
cb:[null, Validators.required],
productFormGroup: this.productFG
}),
changeSelection(id) {
this.checkedIDs = []
this.selectedItemsList = this.DisplayProductList.filter(product => product.isChecked);
this.selectedTypes = this.selectedItemsList.reduce((a, i) => {
if(a[i['policy_type']]){
a[i['policy_type']] = [...a[i['policy_type']], i];
}else{
a[i['policy_type']] = [i];
}
return a;
}, {});
this.checkedIDs = this.selectedItemsList.map(item => ({ id: item.id }));
const item = this.DisplayProductList.find(p => p.id === id);
if (item.isChecked) {
const fg: FormGroup = this.createFormGroup(item);
this.productFArray.push(fg);
return;
}
CodePudding user response:
take one variable like this ...
isCheckBoxSelected:boolean=false;
and make one method like this and put in (change) ...
checkboxChanged(){
this.isCheckBoxSelected=!this.isCheckBoxSelected;
}
and in HTML instead of below code
[value]="true"
use this code
[value]="isCheckBoxSelected"
and change your if condition like this ...
*ngIf="submitted && !isCheckBoxSelected"
CodePudding user response:
I passed an event in onclick method and added these lines. it worked.
changeSelection(id,e) {
if(!e.target.checked){
let ind = this.checkedIDs.findIndex(x =>x.id==id)
if(ind != -1){
this.checkedIDs.splice(ind,1)
}
}else{
this.isAtleastPolicyError = false;
}
submit method:
if (this.clusterForm.invalid || this.checkedIDs.length == 0) {
this.isAtleastPolicyError = true;
return
}