Issue
I have generated list of mat slide toggle's using for loop, but what want is, when I click on one slide toggle other slide toggles should be disabled.
my code:
HTML:
<div class="row">
<div class="col-md-6 mt-2" *ngFor="let data of attributes">
<mat-slide-toggle>{{data}}</mat-slide-toggle>
</div>
</div>
TS:
attributes = ["Last 7 days", "Last 30 days", "Last 60 days"]
In this scenario, when I click on "Last 7 days" slide toggle, then "Last 30 days", "Last 60 days" should be disabled,
Solution
Change your
attributesarray to hold objects with the attribute and a property for the disabled state. E.g.options = [{id: 1, title: "Last 7 days", disabled: false}, ...];Add anidto identify which one was toggled.Bind the
disabledproperty to thedisabledinput and theidto theidattribute.See the API Docs and use
@Output() change: EventEmitter<MatSlideToggleChange>event to call a function which iterates over your array and set all disabled flags totrueexcept the one which triggered the event.Do the same thing for enabling all toggles.
<div *ngFor="let data of options">
<mat-slide-toggle
[id]="data.id"
[disabled]="data.disabled"
(change)="disableAll($event)">
{{data.title}}
</mat-slide-toggle>
</div>
options = [
{ id: 1, title: "Last 7 days", disabled: false },
{ id: 2, title: "Last 30 days", disabled: false },
{ id: 3, title: "Last 60 days", disabled: false }
];
disableAll(ev: MatSlideToggleChange) {
if (ev.checked) {
this.options
.filter(opt => opt.id != ev.source._elementRef.nativeElement.id)
.forEach(opt => (opt.disabled = true));
} else {
this.options.forEach(opt => (opt.disabled = false));
}
}
Here's a demo: https://stackblitz.com/edit/angular-fhmsyp?file=src%2Fapp%2Fslide-toggle-overview-example.ts
Answered By - kai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.