Tamás
Tamás

Reputation: 39

Material datepicker filtering

I'm trying to get the filtering to work. I've modified the sample, and can't figure it out why this does not work. I want to disable all days, except the ones in testDates array. "found valid day" is logged out correctly, and yet the days are not selectable.

  myFilter = (d: Date): boolean => {
    const testDates: Date[] = [
      new Date('2018-08-30T00:00:00+02:00'),
      new Date('2018-08-28T00:00:00+02:00'),
      new Date('2018-08-21T00:00:00+02:00'),
      new Date('2018-08-23T00:00:00+02:00')
    ]
    testDates.forEach(item => {
      if (item.toDateString() == d.toDateString()) {
        console.debug("found valid day:" + d);
        return true;
      }
    });
    console.debug("invalid day:" + d);
    return false;
  }

Here it is in stackblitz: https://stackblitz.com/edit/angular-6fgvsx?embed=1&file=app/datepicker-filter-example.ts

Upvotes: 0

Views: 4129

Answers (2)

Stas Bidenko
Stas Bidenko

Reputation: 156

use myFilter as the following code:

myFilter = (d: Date): boolean => {
    const testDates: Date[] = [
      new Date('2018-08-30T00:00:00+02:00'),
      new Date('2018-08-28T00:00:00+02:00'),
      new Date('2018-08-21T00:00:00+02:00'),
      new Date('2018-08-23T00:00:00+02:00')
    ]

    return testDates.findIndex(testDate => d.toDateString() == testDate.toDateString()) >= 0;
  }

Upvotes: 4

heunetik
heunetik

Reputation: 577

Save the return value to a variable, then it will work.

let x = false;
testDates.forEach(item => {
    if (item.toDateString() == d.toDateString()) {
        x = true;
    }
})
return x;

StackBlitz Example

Upvotes: 1

Related Questions