-3

I'm very demoralized because I've been trying to do something for days without success. I'm trying to create a search filter for each column I have in my table (filled dynamically, except the columns name).

I've created my table, gilled with data from an api, but now I have no idea how to filter column by column according to an input inserted from some box above.

This is an example of what I would like.

enter image description here

P.s. I'm using angular and typescript

1 Answers1

0

In this SO there're an answer to give you some clues:

  1. Create a formGroup

  2. In subscribe equal the dataSource.filter to an string, the JSON.stringify(res);

  3. create a function customFilter that received a element and the "filter" (the string before that you should parse using JSON.parse ) and return true if mtach with the values

Update Using the "typical" Periodic elements, we can use a FormGroup in the way

  form = new FormGroup({
    position: new FormControl(''),
    name: new FormControl(''),
    weight: new FormControl(''),
    symbol: new FormControl(''),
    filterOn: new FormControl(false),
  });

See that we can use a FormControl "filterOn". So, we can use a custom filter like

  customFilter = (data: PeriodicElement, filter: string) => {
    const filterData = JSON.parse(filter);
    let ok: boolean = true;
    if (!filterData.filterOn) return true;
    if (filterData.position) ok = data.position == filterData.position;
    if (filterData.name)
      ok = ok && data.name.toUpperCase().indexOf(filterData.name) >= 0;
    if (filterData.weight)
      ok = ok && ('' + data.weight).indexOf(filterData.weight) >= 0;
    if (filterData.symbol)
      ok = ok && data.symbol.toUpperCase().indexOf(filterData.symbol) >= 0;
    return ok;
  };

Ah!, when we subscribe to valueChanges, we transform to upperCase or another way our values

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.filterPredicate = this.customFilter;
    this.form.valueChanges.subscribe((res: any) => {
      res.name = res.name.toUpperCase();
      res.symbol = res.symbol.toUpperCase();
      res.weight = '' + res.weight;
      this.dataSource.filter = JSON.stringify(res);
    });
  }

The button filter toggle the variable "filterOn" and use setValue to give value to the formControl "filterOn"

  filterToggle() {
    this.filterOn = !this.filterOn;
    this.form.controls.filterOn.setValue(this.filterOn);
  }

The whole stackblitz

Eliseo
  • 50,109
  • 4
  • 29
  • 67