How can you add an "index" to the Angular Material Datepicker Filter

390 Views Asked by At

So I have to make quite a complicated filtering (which I managed to do it) but now I'm pretty much stuck, I have to use the same filter (or at least the same logic) to more date pickers (worth to be mentioned that the number of date pickers is dynamically generated), but each date picker has different dates that must filtered.

(By the way, I have these date pickers in a Material table, I have the index of each row so I can retrieve that datepicker's filtered dates from the backend)

I thought I could do this :

 <mat-date-range-input [rangePicker]="picker" [dateFilter]="date_picker_filters(i)">

Where "i" is the row index of the Mat Table

In the component I did this :

  public date_picker_filters= (d: Date, i: number): boolean => {

  ................... filtering logic .....................

  }

But it doesn't really work.

Any ideas?

2

There are 2 best solutions below

0
AudioBubble On

After researching the internet, still no response so I found a way to do this, not a really clean way, but I think it's the only option :

You have to create a variable in the component

var current_index: number

Also you have to make a function that is going to assign the value of that row (or whatever index you have) to this variable

public current_index_assing(current_index: number) {
  this.current_index = current_index
}

(I use the Mat Daterange picker that has a button to open the date selection panel) Then, in the html file, you execute the function that sets the index when you click on the calendar icon :

<mat-datepicker-toggle matSuffix [for]="picker" (click)="current_index_assing(index)"></mat-datepicker-toggle>

Again, I don't think this is a clean approach, but it works

0
Eliseo On

we can think in some like:

/**this NOT WORK***/
<mat-date-range-input [rangePicker]="picker"
         [dateFilter]="date_picker_filters(i)">


date_picker_filters(index:number){
   return (date:any)=>{
      console.log(index,date)
      ..your logic can use "index"..
      return true;
   }
}

but our app "crash" because we are puting a function in .html and Angular check if change, see this Jurgen Van de Moere's article , so we can take another aproachh

Define an array of filters

filters:any[]=[]

And in ngOnInit, give value, so many we are interested (in the code I use only 2 mat-datepickers)

ngOnInit(){
    [0,1].forEach(x=>{
      this.filters[x]=this.date_picker_filters(x)
    })
  }

Then we can use

<mat-date-range-input [rangePicker]="picker" 
    [dateFilter]="filters[i] || null">

A stackblitz