Hide/Show form field(s) on mat-checkbox check Angular

1.1k Views Asked by At

I am trying to show and hide the search filter input field which is basically my form field with the check of a checkbox that is in my search filter button.

I am using *ngIf here to show and hide the field. It doesn't seem to work the issue is, it always returns the boolean value of the last checked checkbox from the dropdown filter. I'm not sure what am I doing wrong. I've got two arrays out of which one has all the available filter options and another one is where I'm pushing my filter when checked. I only want to display those input fields which are checked.

  hideFilter(param: any) {
    this.showTheseFilter.forEach((item: any, index) => {
      if (param == item) {
        this.hide = true;
      } else {
        this.hide = false;
      }
    });
    return this.hide;
  }

My stackblitz URL: https://stackblitz.com/edit/angular-zub6zk-axvvdk?file=src/app/table-basic-example.ts

1

There are 1 best solutions below

0
On BEST ANSWER

I fixed it here https://angular-zub6zk-rqler6.stackblitz.io

https://stackblitz.com/edit/angular-zub6zk-rqler6?file=src/main.ts

The issue was with the hideFilter function.

I suggest you use a pipe for the function which you can reuse when you need to. Sometime like

import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({
   name : 'arrIncludesItem'
})
export class ArrIncludesItemPipe implements PipeTransform {
   transform(array: any[], item: any) : boolean{
      if(!item || !array || !array.length) return false
      return array.includes(item);
   }
}

Then you can use it as

<element *ngIf="showTheseFilter: arrIncludesItem: 'filterByDateRange'"></element>