如何在Angular中将keydown.control与自定义点击函数结合使用?

huangapple go评论74阅读模式
英文:

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.

如何在Angular中将keydown.control与自定义点击函数结合使用?

<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.

&lt;div class=&quot;nums&quot;&gt;
  &lt;div *ngFor=&quot;let num of [1, 2, 3, 4, 5]&quot;&gt;
      &lt;span class=&quot;num&quot; 
      (click)=&quot;select(num, $event.ctrlKey)&quot;&gt;{{ num }}&lt;/span&gt;
  &lt;/div&gt;
&lt;/div&gt;

Note that I'm using Set instead of an array to easily avoid duplicates.

readonly selectedNums = new Set&lt;number&gt;();

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.

huangapple
  • 本文由 发表于 2023年2月27日 19:14:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定