我已经构建了一个使用host事件监听器订阅键盘事件的指令。当按下退出键时,我正在触发像这样的输出事件
@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) {
if (kbdEvent.keyCode === 27) {
this.CloseEvent.emit();
}
}
我对子元素有这个指令。当按下转义键时,我想只为新订阅的元素触发输出事件。问题是,当我单击转义键时,事件将根据层次结构顺序触发。我在这里做了一个演示:https://plnkr.co/edit/FfnHAtxl2zcHsu0JilKt
重现的步骤:
预期行为:
答案 0 :(得分:1)
执行此操作的一种方法是使用KeyboardEvent
事件发送close
。然后,您可以检查事件的defaultPrevented
是否设置为true,否则执行删除并preventDefault
。
我做了一些优化。您可以使用'document:keyup.ESC'
绑定,然后立即设置(close)
,它将使用CloseDirective
我-应用
@Component({
selector: 'my-app',
template: `
<h4>Add Multiple Child And Click On Escape key</h4><br>
<div *ngFor="let child of childArray;let i = index">
<div style="display:flex;flex-direction:row">
<my-chid (close)="onClose($event)" [index]="child"></my-chid>
<button (click)="deleteChild(i)">Delete</button>
</div>
</div>
<button (click)="addChild()">Add Child</button>
`,
})
export class App {
childArray: any[] = [];
addChild(): void {
this.childArray.push(this.childArray.length);
}
onClose(event: KeyboardEvent): void {
if (!event.defaultPrevented) {
event.preventDefault();
this.deleteChild(this.childArray.length - 1);
}
}
deleteChild(index: number): void {
this.childArray.splice(index, 1);
}
}
我的孩子
@Component({
selector: 'my-chid',
template: `
<div>
I am child {{index}}
</div>
`,
})
export class MyChild {
@Input()
public index: number;
}
关闭指令
@Directive({
selector: '[close]'
})
export class CloseDirective {
@Output() close: EventEmitter<KeyboardEvent> = new EventEmitter<KeyboardEvent>();
@HostListener('document:keyup.ESC', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) {
this.close.emit(kbdEvent);
}
}