Home > Software engineering >  How can I write the javascript for changing the mat-slider labels with range?
How can I write the javascript for changing the mat-slider labels with range?

Time:11-28

Initially, I am using a mat-slider I need to change the label as per the range. But I don't know how to write JavaScript for different labels can anyone help me as of now I am a Fresher.

mat-slider I need this one

CodePudding user response:

When we have a "input", a good aproach is use or [(ngModel)] or [formControl] to asign to a variable the value of the "input". The advantage of use a FormControl is that we can subscribe to valueChange. That's, each time the input change, the formControl change and, if we subscribe, execute an action. We can use async pipe to make the subscription.

We are going to!!

  min = 0;
  max = 10;
  states = ['sad', 'medium', 'happy', 'great'];
  control = new FormControl(0);
  state$ = this.control.valueChanges.pipe(
    startWith(this.control.value),
    map((x: any) => {
      return this.states[
        Math.round((x * (this.states.length - 1)) / 
           (this.max - this.min))   this.min
      ];
    })
  );

See that you use "map" rxjs operator to transform the response to valueChange -the value of the FormControl- to a string. we get the Math.round to get a value from 0 to this.states.length - 1 and return the element of the array "this.states"

The .html

<div>
  <mat-slider [min]="min" [max]="max">
    <input matSliderThumb [formControl]="control" />
  </mat-slider>
  {{state$|async}}
</div>

the stackblitz

CodePudding user response:

Template

<h1>How do you feel?</h1>

<mat-slider min="1" max="5" step="1">
  <input matSliderThumb [formControl]="mood" />
</mat-slider>
{{ moodDisplayText$ | async }}

Component

const MOOD_MAPPING: Record<number, string> = {
  1: 'very sad',
  2: 'sad',
  3: 'ok',
  4: 'happy',
  5: 'very happy',
};

@Component({
  selector: 'slider-overview-example',
  templateUrl: 'slider-overview-example.html',
  styleUrls: ['slider-overview-example.css'],
})
export class SliderOverviewExample {
  mood: FormControl = new FormControl(1);
  moodDisplayText$ = this.mood.valueChanges.pipe(
    startWith(this.mood.value),
    map((value) => MOOD_MAPPING[value])
  );
}

Stackblitz: https://stackblitz.com/edit/angular-jf9iqa?file=src/app/slider-overview-example.ts

  • Related