6

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);
        }
    }
}
4
  • is there any error on keypress ? Commented Mar 22, 2017 at 6:09
  • 1
    Seems to be working here: plnkr.co/edit/aIY3B7qE17hGOp6Yc7PI?p=preview Commented Mar 22, 2017 at 6:11
  • @PardeepJain it isn't giving any error on keypress Commented Mar 22, 2017 at 6:53
  • 1
    @echonax I see your code, it's working, but in my case it doesn't seem to work for keypress, but it is working for keyup and keydown Commented Mar 22, 2017 at 6:54

3 Answers 3

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. :)

Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.