В коде ниже 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
}
}