英文:
How to combine keydown.control with a custom click function in Angular?
问题
如何以随机顺序选择多个数字元素,并通过按下控制键 (CTRL)
和单击元素将它们存储到数组中,例如从5中选择2和4?经过多次尝试,我无法将单击事件与@Hostlistener
结合使用。
@Hostlistener('window.keydown.control', ['$event'])
onKeyDown(event: KeyboardEvent) {
console.log('按下了控制键');
}
onNumClick(num: number) {
this.selectedNums.push(num);
}
请注意,代码部分已被翻译,如果有其他问题,请提出。
英文:
How to select multiple number elements in random order and store them to an array by pressing down the control key (CTRL)
and clicking the element, e.g. 2 and 4 from 5? After many attempts I was not able to combine the click event with @Hostlistener
.
<div class="nums">
<div *ngFor="let tempNum of [1, 2, 3, 4, 5]">
<span class="num" (click)="onNumClick(tempNum)">{{ tempNum }}</div>
</div>
</div>
@Hostlistener('window.keydown.control', ['$event'])
onKeyDown(event: KeyboardEvent) {
console.log('Control key clicked');
}
onNumClick(num: number) {
this.selectedNums.push(num);
}
答案1
得分: 2
一个非常简单的解决方案可以是这样的 - 只需检查点击事件是否已设置ctrlKey
标志,并相应地修改行为。
<div class="nums">
<div *ngFor="let num of [1, 2, 3, 4, 5]">
<span class="num"
(click)="select(num, $event.ctrlKey)">{{ num }}</span>
</div>
</div>
请注意,我使用的是Set
而不是数组,以轻松避免重复。
readonly selectedNums = new Set<number>();
select(num: number, selectMulti: boolean): void {
if (!selectMulti) {
this.selectedNums.clear();
}
this.selectedNums.add(num);
}
请记住,这显然不适用于移动设备。对于移动用户,您将不得不提供替代方案,例如复选框或长按操作。
英文:
A really simple solution would be something like this - just check if the click event has the ctrlKey
flag set, and modify behavior accordingly.
<div class="nums">
<div *ngFor="let num of [1, 2, 3, 4, 5]">
<span class="num"
(click)="select(num, $event.ctrlKey)">{{ num }}</span>
</div>
</div>
Note that I'm using Set
instead of an array to easily avoid duplicates.
readonly selectedNums = new Set<number>();
select(num: number, selectMulti: boolean): void {
if (!selectMulti) {
this.selectedNums.clear();
}
this.selectedNums.add(num);
}
Remember that this obviously won't be usable on mobile devices. For mobile users you'll have to offer an alternative, such as checkboxes or longpress.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论