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?
"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
formatRateLabel
in your .ts file to be a functional such asformatRateLabel = (v: boolean) => {
return (value: number) => {
var myLocalVariable = v;
... // Do something
}
}
formatRateLabel
in your .html file to be[displayWith]="formatRateLabel(someProperty)"
so that this variable someproperty
can be passed into your function.
You have few ways to fix this issue but the simplest and most appropriate solution to fix this issue is by using function expression. Simply redefine the formatRateLabel
in the following way.
formatRateLabel = (value: number) => {
var myLocalVariable = this.someProperty;
}
Hopefully this should work.
As I found, the really easiest way is add this code to the constructor
function of your component:
this.formatLabel = this.formatLabel.bind(this);
then your function will be applied with right this
linked.
A bit late but i find this one a better solution. Just bind this to the html component, like this:
<mat-slider thumbLabel [displayWith]="formatRateLabel.bind(this)">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With