5

keypress event not firing with enter key in angular 2, following is the html and angular 2 code:

HTML

<input [(ngModel)]="filters[i]" type="number" size="30" pInputText (keypress)="filterByField($event, col.field, fieldType.TEXT)" class="{{'input-'+col.field}}" title="Only numbers are allowed" />

Angular 2

filterByField(event, field, fieldType){
    console.log(event)
    if(fieldType === this.fieldType.DD){
        event.originalEvent.stopPropagation();
        this.resetFilterBy(event.value, field);
        this.loadData(null, true);
    }
    else if(fieldType === this.fieldType.TEXT){
        let charCode = (event.which) ? event.which : event.keyCode;
        console.log(charCode)
        if (charCode == 101 && field == this.fields.TASKID.field){
            event.preventDefault();
            return false;
        }
        if((charCode === 13  && event.target.value.trim() !== "") || (charCode === 8) || (charCode === 46)) {
            let filterValue = event.target.value;
            this.resetFilterBy(filterValue, field);
            this.loadData(null, true);
        }
    }
}
A. A. Sebastian
  • 540
  • 1
  • 7
  • 19
Sahil Agarwal
  • 799
  • 4
  • 12
  • 19

3 Answers3

7

If you need to only listen for enter keypress event then you can use "keyup.enter" event in your html like:

<input #box (keyup.enter)="onEnter(box.value)">

Hope this helps. :)

ajinkya udgirkar
  • 223
  • 1
  • 10
0

Probably it's breaking because of the extra parameters at filterByField function

(keypress)="filterByField($event, col.field, fieldType.TEXT)"

passed as part of the call, Make sure all the properties you are binding in HTML are defined in component.

Yoav Schniederman
  • 5,253
  • 3
  • 28
  • 32
HGrover
  • 225
  • 1
  • 10
0
@Component({
    selector: 'my-search',
    template: `
              <input #criteria type='text' placeholder="Enter criteria" (keypress)="preventNumbers($event)"  />
              <button (click)="search(criteria.value)">Search</button>
              `
})

export class MySearchComponent { 
    preventNumbers(e) {
        console.log(e.keyCode);
        if (e.keyCode >= 48 && e.keyCode <= 57) {
            // we have a number
            return false;
        }
    }
    search(criteria) {
        console.log("search for " + criteria);
    }
}
Yoav Schniederman
  • 5,253
  • 3
  • 28
  • 32