gpt4 book ai didi

angular - 如何在angular2中为左右键添加事件?

转载 作者:太空狗 更新时间:2023-10-29 17:24:45 24 4
gpt4 key购买 nike

我已经编写了如下所述的代码。截至目前,列表项仅在单击鼠标时被选中。即使我按下键盘上的上下箭头,我也想遍历列表。如何使用 angular2 实现这一点?

import { Component } from '@angular/core';

export class Hero {
name: string;
}

const HEROES: Hero[] = [
{ name: 'STWX1' },
{ name: 'STWX2' },
{ name: 'STWX3' },
{ name: 'STWX4' }
];

@Component({
selector: 'my-app',
template: `
<div style="display: inline-block; width = 200px; ">
<ul class="heroes">
<li *ngFor="let hero of heroes" (click)="onSelect(hero)"
[class.selected]="hero === selectedHero">
<p>{{hero.name}}</p>
</li>
</ul>
</div>'

, 风格:[...]})

export class AppComponent  {
name = 'Angular1';
testRequestId = '3224';
heroes = HEROES;
selectedHero: Hero;

goToDivClick() {
return HEROES;
}

onSelect(hero: Hero): void {
this.selectedHero = hero;
}

最佳答案

<li *ngFor="let hero of heroes;let index=index" 
[style.background-color]="index === selectedIndex ? 'yellow' : null"
(click)="onSelect(hero)"
(keydown.ArrowLeft)="onLeft($event)" (keydown.ArrowRight)="onRight($event)"
(keydown.ArrowUp)="onUp($event)" (keydown.ArrowDown)="onDown($event)"

另见 https://github.com/angular/angular/blob/630d93150a58581a0d474ebf1befb5d09b6813c5/modules/angular2/src/platform/browser/browser_adapter.dart

关于angular - 如何在angular2中为左右键添加事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com