在angular2中,输入键是否触发页面上的任何点击事件? [英] In angular2 does enter key trigger any click event on the page?

查看:146
本文介绍了在angular2中,输入键是否触发页面上的任何点击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码 removeSelectedCountry()中,应该在点击span元素时调用 handleKeyDown($ event)应该在div上有一个keydown事件时调用。

In the code below removeSelectedCountry() should be called when the span element is clicked and handleKeyDown($event) should be called when there is a keydown event on the div.

@Component({
    selector: "wng-country-picker",
    template: `
    <ul class="CountryPicker-selected" *ngIf="selectedCountries.length > 0">
    <li *ngFor="let country of selectedCountries">
        <span class="Pill Pill--primary" (click)="removeSelectedCountry(country)">
        {{ country.name }}
        </span>
    </li>
    </ul> 
    <div (keydown)="handleKeyDown($event)" class="CountryPicker-input"></div>
`,
providers: [CUSTOM_VALUE_ACCESSOR]
})

但是每按一次Enter键,都会调用 removeSelectedCountry()

But removeSelectedCountry() is called every time enter key is pressed.

为了使代码工作,我不得不将点击事件更改为 mousedown 事件。
现在可以正常工作。

To make the code work I had to change the click event to mousedown event. It works fine now.

任何人都可以解释为什么输入密码会触发点击事件?

Can anyone explain why enter key would trigger click event?

@Component({
    selector: "wng-country-picker",
    template: `
    <ul class="CountryPicker-selected" *ngIf="selectedCountries.length > 0">
    <li *ngFor="let country of selectedCountries">
        <span class="Pill Pill--primary" (mousedown)="removeSelectedCountry(country)">
        {{ country.name }}
        </span>
    </li>
    </ul> 
    <div (keydown)="handleKeyDown($event)" class="CountryPicker-input"></div>
`,
providers: [CUSTOM_VALUE_ACCESSOR]
})

添加类snipppet

Adding class snipppet

export class CountryPickerComponent {

private selectedCountries: CountrySummary[] = new Array();

private removeSelectedCountry(country: CountrySummary){
    // check if the country exists and remove from selectedCountries
    if (this.selectedCountries.filter(ctry => ctry.code === country.code).length > 0)
    {
        var index = this.selectedCountries.indexOf(country);
        this.selectedCountries.splice(index, 1);
        this.selectedCountryCodes.splice(index, 1);
    }
}

private handleKeyDown(event: any)
{
    if (event.keyCode == 13)
    {
       // action
    }
    else if (event.keyCode == 40)
    {
        // action
    }  
    else if (event.keyCode == 38)
    {
        // action
    }    
}


推荐答案

对于ENTER键,为什么不使用(keyup.enter)

For ENTER key, why not use (keyup.enter):

@Component({
  selector: 'key-up3',
  template: `
    <input #box (keyup.enter)="values=box.value">
    <p>{{values}}</p>
  `
})
export class KeyUpComponent_v3 {
  values = '';
}

这篇关于在angular2中,输入键是否触发页面上的任何点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆