简体   繁体   English

按键事件没有使用角键2中的输入键触发

[英]keypress event not firing with enter key in angular 2

keypress event not firing with enter key in angular 2, following is the html and angular 2 code: keypress事件没有使用角度2中的回车键触发,以下是html和angular 2代码:

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

If you need to only listen for enter keypress event then you can use "keyup.enter" event in your html like: 如果你只需要监听enter keypress事件,那么你可以在你的html中使用“keyup.enter”事件,如:

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

Hope this helps. 希望这可以帮助。 :) :)

Probably it's breaking because of the extra parameters at filterByField function 由于filterByField函数的额外参数,可能会破坏它

(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. 作为调用的一部分传递,确保在HTML中绑定的所有属性都在组件中定义。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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