Angular2-单击添加类到项目 [英] Angular2 - Add class to item on click

查看:65
本文介绍了Angular2-单击添加类到项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆列表项,一旦单击它们,我想突出显示它们.对于我来说,这在jQuery甚至JavaScript中都很容易实现,但是当涉及到Angular2时我迷路了.

I have a bunch of list items and would like to highlight each one once it's clicked. This is easy for me to do in jQuery or even JavaScript but I'm lost when it comes to Angular2.

<ul>
   <li [attr.data-selected]="false" (click)="highlightItem($event)" [class.highlight]="isHighlighted($event)" *ngFor="#item of items"> {{item}} </li>
</ul>

我的组件

export class HelloWorld {
    items = ["pineapples", "apples", "tomatoes", "bread"];

    highlightItem(event) {
        event.target.setAttribute("data-selected", "true");
   }

   isHighlighted(event) {
       return event.target.getAttribute("data-selected") == "true";
    }
}

不确定我的错误在哪里或者我使用的方法是否错误

Not sure where my mistake is or if I'm using a wrong method

推荐答案

您需要在类中创建一个数组,以存储项目的突出显示状态:

You need to make an array in your class to store highlight status of an item:

hightlightStatus: Array<boolean> = [];

在与ngFor关联的模板中声明局部变量:

Declare local variable in the template associated with ngFor:

<ul>
   <li [attr.data-selected]="false" 
       (click)="hightlightStatus[i]=!hightlightStatus[i]" 
       [class.highlight]="hightlightStatus[i]" 
       *ngFor="let item of items, let i = index"> 
       {{item}} 
   </li>
</ul>

这篇关于Angular2-单击添加类到项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆