Reputation: 101
I am using ngModel
in Angular 5 and here is Html
<span *ngFor="let id of Ids">
<input class="checkbox" type="checkbox" [(ngModel)]="strManyModel[id]" (change)="setValue($event)" [value]="id">
</span>
And here is typeScript
setValue(e){
if(selectedChkBox > 5){
this.strManyModel[e.target.value] = false;// if check box more than 5 selected , unselect this one
}
}
I want to restrict check boxes to selected once 5 check boxes is being selected. At first click once 5 is selected , ia m able to restrict to checkbox to select , but at same time if it is again select it is going to select. Want to restrict check boxes to check once 5 is checked. At a time at max 5 check boxes to select out of many. One can select other one only if he uncheck any older one which was selected in case 5 is selected.
Upvotes: 2
Views: 2765
Reputation: 73337
If I understand you correctly, you want to disable other checkboxes when 5 are chosen and keep the unchecked disabled until checked boxes are less than 5...
What you could do, have objects in your array, witch a checked
property to keep track on the checked state, as well as introduce a new boolean and a "counter" to keep track of how many checkboxes are checked. Disable the checkboxes that are not checked and when the maximum of 5 checkboxes have been chosen:
<div *ngFor="let chk of checkBox; let i = index">
<input [(ngModel)]="chk.checked"
type="checkbox"
[disabled]="!chk.checked && maxNo"
(change)="onChange($event.target.checked)">{{chk.name}}
</div>
Where the array would consist of objects with name
and checked
property. Then your change event would increment/decrement based on checked checkboxes and switch the boolean flag maxNo
:
onChange(isChecked: boolean) {
isChecked ? this.amt++ : this.amt--;
this.maxNo = this.amt === 5 ? true : false;
}
Here's a
Upvotes: 2
Reputation: 249
Create additional class property like:
public maxElementCheckbox = 5;
Then use a function:
public disableCheckbox(): boolean {
return Ids.length >= this.maxElementCheckbox;
}
Template is:
<input class="checkbox" [disabled]="disableCheckbox()" type="checkbox" [(ngModel)]="strManyModel[id]" (change)="setValue($event, i)" [value]="id">
Upvotes: 3
Reputation: 18085
A possible solution might be:
<span *ngFor="let id of Ids; index as i">
<input class="checkbox" type="checkbox" [(ngModel)]="strManyModel[id]" (change)="setValue($event, i)" [value]="id">
</span>
setValue(e, index){
if(Ids.length >= 5){
strManyModel[index] = false;
}
}
Upvotes: 0