Issue
I’m using Angular Material v6
.
Documentation says that displaywith
it’s a “Function that will be used to format the value before it is displayed in the thumb label.” And it ought to be used like that:
<mat-slider thumbLabel [displayWith]="formatRateLabel" [value] = 'movie.mark'>
</mat-slider>
In my component class I have a formatRateLabel
function:
formatRateLabel(value: number) {
if (!value)
return 0;
return "HI!"; //just for demonstration
}
What I need is to get values of my component from inside that function. I usually do such thing by using this
keyword inside some function. But when I do it from that fornatRateLabel
function properties of my component are undefined. As I understand it’s kind of scope problem. Word this
in this function has access to the all properties and functions of mat-slider only. But I need the access to my component’s properties from that function. Let me show:
Here’s my component:
@Component({
templateUrl: './movieLibrary.component.html',
styleUrls: ['./movieLibrary.component.css']
})
export class MovieLibraryComponent{
someProperty : boolean = true;
formatRateLabel(value: number){
var myLocalVariable = this.someProperty;// debug showed it's as undefined. Why?
}
}
I’ve tried to pass some parameters to formatRateLabel
like this
[displayWith]="formatRateLabel(movie.mark)"
but in that case thumb label becomes empty, so that’s not working either.
Any suggestions?
Solution
“this” in your formatRateLabel
function is pointed to the slider not your component itself.
So, you need to tell it what “this” should be.
The simplest solution is to
- change your
formatRateLabel
in your .ts file to be a functional such as
formatRateLabel = (v: boolean) => {
return (value: number) => {
var myLocalVariable = v;
... // Do something
}
}
- change your
formatRateLabel
in your .html file to be
[displayWith]="formatRateLabel(someProperty)"
so that this variable someproperty
can be passed into your function.