Search code examples
htmlangularangular-materialdrag-and-dropangular-cdk

AngularMaterial mat-slide-toggle toogle working only for the first component


I have an angular project I am developing using angular material for a slide toggle and text fields, and cdk drag and drop for drag and drop functionality. I am pretty new to angular libraries and angular in general.

I have run into an issue where the slide toggle is only toggling the first element inside an *ngFor loop. I have tried adding a let i = index to the ngFor and it is always passed as 0 no matter which toggle you select, however if I place {{ i }}, it will show up as the correct index. I am at a loss.

https://stackblitz.com/edit/angular-yezv9a

If you go to the project at that link, and toggle the test 2 or 3 toggle, it will shift the first 1 and I can not seem to figure out why

Any help is appreciated


Solution

  • If I understand you correctly, There is one issue in your code is mat-slide-toggle element has an id which is repeating in ngFor

    <mat-slide-toggle id="toggle" color="primary" (change)="onToggle(button)" [checked]="button.enabled"></mat-slide-toggle>

    I removed the id attribute and found working correctly, based on my understanding you can find a fork of working example in below url

    https://angular-yezv9a-bac1jz.stackblitz.io/