What is the best way to activate the filter in primeNG datatables angular 2 only when the enter key is pressed?

I'm utilizing PrimeNG datatables in Angular 2 and I want to know how to make the filter of PrimeNG datatable activate only when the user presses the enter key.

Here is the base code:

HTML:

<div class="container-fluid single-col-full-width-container">
  <div class="ui-widget-header ui-helper-clearfix" style="padding:4px 10px;border-bottom: 0 none">
    <i class="fa fa-search" style="float:right;margin:4px 4px 0 0"></i>
    <input #gb type="text" pInputText size="50" style="float:right" placeholder="Filter...">
  </div>
  <div class="ContentSideSections Implementation">
    <p-dataTable
      #reprintGrid
      [value]="datasource"
      [(selection)]="jobs"
      (onRowSelect)="onRowSelect($event)"
      [paginator]="true"
      [rows]="10"
      [responsive]="true"
      [totalRecords]="totalRecords"
      [lazy]="true"
      (onLazyLoad)="getNewDatasource($event)"
      [pageLinks]="10"
      [rowsPerPageOptions]="[10, 25, 50, 100]"
      [globalFilter]="gb"
    >
      <p-column [style]="{'width':'38px'}" selectionMode="multiple"></p-column>
      <p-column *ngFor="let col of columnDefs" [field]="col.field" [header]="col.headerName" [sortable]="true">
      </p-column>
    </p-dataTable>
  </div>
</div>

TS file:

export class ReprintModuleComponent implements OnDestroy, OnInit {

  columnDefs = [
    {
      headerName: 'Athlete',
      field: 'athlete'
    },
    {headerName: 'Age', field: 'age'},
    {headerName: 'Country', field: 'country'},
    {headerName: 'Year', field: 'year'},
    {headerName: 'Date', field: 'date'},
    {headerName: 'Sport', field: 'sport'},
    {headerName: 'Gold', field: 'gold'},
    {headerName: 'Silver', field: 'silver'},
    {headerName: 'Bronze', field: 'bronze'},
    {headerName: 'Total', field: 'total'}
  ];

  datasource=[];
  jobs = [];
  totalRecords: number;
  pngService: PrimeNgCommonService;
  @ViewChild('reprintGrid') reprintGrid;
  @ViewChild('gb') globalFilter;

  getNewDatasource(event: LazyLoadEvent) {
    let obsResponse = this.pjService.sampleData();
    obsResponse.subscribe(
      res => {
        this.datasource = res;
        this.totalRecords = res.length;
      }
    );       
  }

  constructor(private pjService: PrintJobService) {
    this.pngService = PrimeNgCommonService.getInstance();
  }

  onRowSelect(event) {

  }
}

Is there a way to customize the filtering behavior of datatables so that it's activated only when the user hits the enter key?

Answer №1

While it may not be officially supported, there is a workaround available by tweaking the filterDelay attribute and utilizing Angular 2's key event feature. Here is a general guideline on how to achieve this:


Typescript file (TS)

import {DataTable} from "primeng/components/datatable/datatable";

@Component({
    templateUrl: '.../some.component.html'
})

export class SomeComponent implements OnInit {
    @ViewChild(('myDT')) dataTableX: DataTable;

    constructor() {}

    ngOnInit() {
        // Set the filter delay value to a high number
        this.dataTableX.filterDelay = 2147483647;
    }

    filter(){
        // Reset filter delay
        this.dataTableX.filterDelay = -1;
    }

    reset(){
        // Set filter delay back to original value
        this.dataTableX.filterDelay = 2147483647;
    }
}

HTML file

<p-dataTable #myDT (keydown.enter)="filter()" (keyup.enter)="reset()" >
    <p-column field="fieldx" header="Column name" [filter]="true"></p-column>
</p-dataTable>

This solution has been tested with:

  • Primeng 1.0.0-beta.17
  • Angular 2.0.0 Final release

The chosen delay number for automatic filtering is approximately 24 days. NaN cannot be used due to browser limitations explained here.

I hope you find this information helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An issue occurred: The module failed to self-register at the specified path: '/node_modules/onnxruntime-node/bin/napi-v3/linux/x64/onnxruntime_binding.node'

Hey there, I'm trying to implement transformer js in my node js application using typescript. The code is located in a file named worker.js. const TransformersApi = Function('return import("@xenova/transformers")')(); const { CLIPVisionModel ...

What are the steps to resolving an issue in a Jest unit test?

In my ReactJs/Typescript project, I encountered an issue while running a unit test that involves a reference to a module called nock.js and using jest. Initially, the import statement was causing an error in the .cleanAll statement: import nock from &apos ...

Issue with Angular app using Azure AD not redirecting to specified path after successful login

My angular webapp is connected to Azure AD/Entra Id for user authentication. The redirect URI in my Azure AD app is set as "http://localhost:4200/translate". Here are my defined routes: const routes: Routes = [ { path: 'translate', path ...

Having trouble launching my angular application in the development environment

My Angular application builds and runs successfully in production mode, but I'm facing issues running it in development mode. When I try the command: npm exec ng serve -c dev --port 4200 --proxy-config proxy.conf.json and add -c dev, I encounter an er ...

Conceal API request details on the network tab

I am currently working on an application built with Angular 10. I was wondering if there is a way to encrypt the request parameters or hide sensitive data. The issue is that anyone who can view the URL has access to both the Bearer token and the request pa ...

Quickly send off an Angular 4 HTTP POST request and move on

I've been experimenting with making a fire and forget request, but none of my attempts seem to be working as expected. The situation is that after completing one subscribable request, I need to redirect to another page. However, before the redirectio ...

Is it advisable to include auto-generated files in an npm package upon publication?

I have a TypeScript NPM package where my build process compiles all *.ts files into myLib.d.ts, myLib.js, and myLib.js.map. In order for my NPM package to function properly, it requires the src/*.ts files as well as the auto-generated myLib.* files. Howe ...

Using typescript, encountering an issue with dynamic import and json file integration

When creating a function to retrieve test data for multiple environments, I encountered an issue: export class DataHelper { public static async getTestData(fileName: string): Promise<any> { return await import(`../${fileName}`); } } Running ...

Tips on how to integrate a Twitter timeline into an Angular 6 application

I've been trying to integrate a Twitter timeline into an Angular 6 application, but I have yet to find a satisfactory solution. Here's what I've attempted so far: Inserted the Twitter generated code from 'publish.twitter.com' int ...

Change the background color of mat-select to match the selected mat-option

<mat-form-field> <mat-select [formControlName]="name"> <mat-option [value]="option.id" [ngStyle]="{backgroundColor: option.color}" *ngFor="let option of list; let i = index" ...

Retrieve all the characteristics accessible of a particular course

I am facing a situation where I have the following class structure: class A { id: number propertyA: string constructor(id: number) { this.id = id } } let a = new A(3) console.log(SomeFunction(a)) // expected output = ['id', ' ...

It appears that the library (@ngx-translate/core) that contains TranslateModule may not be compatible with Angular Ivy, resulting in an error in the Angular application

Encountering an issue after upgrading my Angular app from version 15 to 16 and running npm start. The error message is related to compatibility with Angular Ivy, specifically mentioning @ngx-translate/core. Looking for a newer version of the library or adv ...

CompositeAPI: Referencing HTML Object Template - Error TS2339 and TS2533 when using .value to access Proxy Object

Having trouble referencing an element in VueJS 3 CompositeAPI. In my current implementation, it looks like this: <div ref="myIdentifier"></div> setup() { const myIdentifier = ref(null); onMounted(() => { console.log(myIden ...

Why is TypeScript resorting to using 'any' for specific prop type definitions in React?

Having some trouble with my props typing: export interface ITouchable { isDisabled?: boolean; margin?: Margin; height?: number; bgColor?: string; } The definition of Margin is as follows: type Margin = | { top?: number; bottom?: nu ...

Oops! There seems to be an issue with locating a differ that supports the object '[object Object]' of type 'object', like an Array

I'm currently encountering an error that reads: (ERROR Error: NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the key ...

Do I really need to install @angular/router as a dependency in Angular CLI even if I don't plan on using it?

After creating a new Angular CLI project, I noticed that certain dependencies in the package.json file seemed unnecessary. I wanted to remove them along with FormModules and HttpModules from imports: @angular/forms": "^4.0.0", @angular/http": "^4.0.0", @a ...

Angular - Issue with Function Observable<number> in Development

Currently, I'm working on writing TypeScript code for a component. Within this TypeScript class, I have created a function that is meant to return a number representing the length of an array. My goal is to have this function work like an Observable. ...

Error in Angular FormGroup validation observed while conducting Cypress test

When the formGroup is invalid, a button is disabled. The button only becomes enabled if the conditions below are met: const field = this.formBuilder.group({ fieldType: new FormControl("", [Validators.required]), fieldName: new FormControl("", ...

AngularFire .subscribe function returns undefined when used after map or flatMap operations

Hey there, I'm just diving into AngularFire, Firebase, rxjs and all that good stuff. I've run into a little issue - can anyone shed some light on why my console.log is returning 'undefined' in the following code snippet? this.af.d ...

The data type 'string' cannot be assigned to type [object]

Here's a scenario using an interface: interface Order { symbol: string side: string price: number quantity: number } In my code, I have a section where I am trying to access values within a table. However, it's giving me an error saying tha ...