Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - Does Enter key trigger a click event?

In the code below removeSelectedCountry() should be called when a span element is clicked and handleKeyDown($event) should be called when there is a keydown event on a 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]
})

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

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

Can anyone explain why the Enter key would trigger the 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]
})

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
    }    
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = '';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...