1

I have a little problem becouse I want to use my function in options for bootstrap-datepicker. I have function to check that date is in array of dates:

isInArray(array, value) {
    return !!array.find(item => {
        return item.getTime() == value.getTime()
    });
}

And I want to use it in this option (https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#beforeshowmonth) so I put this to my options:

this.datepickerOptionsForMonths = {
    minViewMode: 1,
    format: "mm-yyyy",
    startDate: this.dateFrom,
    endDate: this.dateTo,
    beforeShowMonth: function (date: Date) {
       return this.isInArray(this.datepickerRange, date.getDate());
    }
};

And now is the problem becouse compilation is completed, everything seems fine but then in console I'm getting errors:

this.isInArray is not a function

Maybe the problem is that I've already used this function in the same body where datepickerOptionsForMonths are (in ngOnInit). Can someone help me?

D.Zet
  • 753
  • 3
  • 11
  • 32
  • Is this line `return item.getTime() == value.getTime()` working ? item is just a variable which may not have getTime method? – brk Jan 16 '19 at 14:05
  • 4
    [`this` does not have the value you expect](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). – VLAZ Jan 16 '19 at 14:05
  • 4
    Also note that you can use `Array.prototype.some` instead of `Array.prototype.find` to avoid the need to cast to boolean. – Jared Smith Jan 16 '19 at 14:09

1 Answers1

6

You are changing the scope of your beforeShowMonth function.

Try using arrow functions instead

beforeShowMonth: (date: Date) => 
  this.isInArray(this.datepickerRange, date.getDate())

Arrow functions maintain the scope of the enclosing object. You can read more abuot it here

Baruch
  • 2,381
  • 1
  • 17
  • 29