angulartypescriptsliderngformat-slider

Get values from multiple mat-sliders dynamically created within ngFor


I am dynamically creating multiple mat-sliders in Angular as follows:

<ng-container *ngFor="let parameter of parameterValues; let i = index;">
  <mat-slider (input)="onInputChange($event)" min="1" max="{{ parameter.length }}" step="1" value="1" id="{{ 'myslider' + i }}"></mat-slider>
</ng-container>

When any of the slider positions are changed, I want to fire an event which subsequently calls another function which receives an array 'sliderValues' which contains each of the dynamically created mat-slider values. I'm attempting this with:

  onInputChange(event: MatSliderChange) {
   for (let i = 0; i < this.results.parameterNames.length; i++) {
    const theid = "myslider" + i;
    var ele = document.getElementById(theid)
    console.log((ele as HTMLInputElement).id + " is the id");
    console.log((ele as HTMLInputElement).value + " is the value");
    this.sliderValues.push((ele as HTMLInputElement).value);
   }
   //some function called here which accepts 'this.sliderValues' as a parameter 
  }

This isn't currently working; I cannot access the values of the sliders. In the console I see 'id' reported correctly but 'value' is 'undefined'. Any help appreciated, I'm open to doing it in a completely different way if needs be.


Solution

  • I found a cleaner way of doing this. The value can be obtained from:

    event.value
    

    and the ID from:

    event.source._elementRef.nativeElement.id
    

    Both 'value' and 'source' are accessible from the MatSliderChange 'event' object