Angular Enter键是否触发单击事件?
在下面的代码中,单击Angular Enter键是否触发单击事件?,angular,dom-events,Angular,Dom Events,在下面的代码中,单击span元素时应调用removeSelectedCountry(),在div上出现keydown事件时应调用handleKeyDown($event) @Component({ selector: "wng-country-picker", template: ` <ul class="CountryPicker-selected" *ngIf="selectedCountries.length > 0"> <li *n
span
元素时应调用removeSelectedCountry()
,在div上出现keydown
事件时应调用handleKeyDown($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" (click)="removeSelectedCountry(country)">
{{ country.name }}
</span>
</li>
</ul>
<div (keydown)="handleKeyDown($event)" class="CountryPicker-input"></div>
`,
providers: [CUSTOM_VALUE_ACCESSOR]
})
添加类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)
:
@组件({
选择器:'key-up3',
模板:`
{{values}}
`
})
导出类KeyUpComponent\u v3{
值=“”;
}
使用(keyup.enter)
Angular可以为我们过滤关键事件。Angular对键盘事件具有特殊语法。我们可以通过绑定Angular的keyup来监听回车键。输入
伪事件。这是正确的解决方案!
<form (keydown)="someMethod($event)">
<input type="text">
</form>
由于按钮没有定义的属性类型,angular可能试图将keyup事件作为提交请求发出,并触发按钮上的click事件
<button type="button" ...></button>
非常感谢DeborahK
@组件({
选择器:'key-up3',
模板:`
{{values}}
`
})
导出类KeyUpComponent\u v3{
剂量测定法(e){
警报(e);
}
}
这对我有用 对于angular 6,有一种新的方法。
在输入标签上添加
(keyup.enter)="keyUpFunction($event)"
其中,keyUpFunction($event)
是您的函数。我个人认为最有用的是:
(mousedown)="callEvent()" (keyup.enter)="$event.preventDefault()
keyup.enter
防止事件在keyup时触发,但它仍然会在keydown时发生,这对我来说很有效。我需要根据所按下的键执行操作,因此(keyup.enter)
没有帮助您可以添加所有3个事件,如keyup.xxxkeyCode
不推荐使用。。使用键
代替。不幸的是,在上面的表单中没有按钮组件。点击是在一个
上触发的,这是一个解决方法的建议,因为其他人都倾向于这样做。准确的回答是,我缺少type属性。
<button type="button" ...></button>
@Component({
selector: 'key-up3',
template: `
<input #box (keyup.enter)="doSomething($event)">
<p>{{values}}</p>
`
})
export class KeyUpComponent_v3 {
doSomething(e) {
alert(e);
}
}
(keyup.enter)="keyUpFunction($event)"
(mousedown)="callEvent()" (keyup.enter)="$event.preventDefault()