在下面的代码中,removeSelectedCountry()
当span
元素被单击handleKeyDown($event)
时应调用,在上发生keydown
事件时应调用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]
})
但是removeSelectedCountry()
每次Enter按键都被调用。
为了使代码正常工作,我不得不将click
事件更改为mousedown
事件。现在工作正常。
谁能解释为什么Enter键会触发click
事件?
@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]
})
添加课程片段:
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
}
}
(keyup.enter)
无济于事