简体   繁体   中英

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM