Angular2 - 单击时将类添加到项目

use*_*735 23 angular

我有一堆列表项,并希望在点击后突出显示每个项目.这对我来说很容易用jQuery甚至JavaScript做,但是当谈到Angular2时我就迷失了.

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

我的组件

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

不知道我的错误在哪里,或者我是否使用了错误的方法

And*_*ich 21

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

hightlightStatus: Array<boolean> = [];
Run Code Online (Sandbox Code Playgroud)

在与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>
Run Code Online (Sandbox Code Playgroud)


Mal*_*k13 10

如果我正确理解了这个问题,我相信你也可以使用angular2中的渲染来获得与你的示例代码类似的代码.对于我自己的项目,我做了以下事情:

在我的模板中,我有:

<li role="presentation" (click)="userTypeSelect($event)" ><a href="#">Local</a></li>
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我有:

import {Renderer} from '@angular/core';
//other imports

export class SignupComponent implements OnInit {

      constructor(private render:Renderer) { }

      userTypeSelect(event:any){
        event.preventDefault()
        this.render.setElementClass(event.target,"active",false);
      }

}
Run Code Online (Sandbox Code Playgroud)

值得注意的是,虽然我没有将它用于项目列表,但我相信它仍然可以工作.

参考渲染器:渲染器Api文档

  • 在我的情况下它没有用.所以我不得不使用`setElementAttribute`.`let oldClasses = event.target.getAttribute('class'); this.renderer.setElementAttribute(event.target,"class",oldClasses +'selected');` (2认同)

Pra*_*obh 7

有很多方法可以实现这一点,而且一切都非常简单.

例子:

<li *ngFor="let n of list" (click)="select(n)" [ngClass]="{active: isActive(n)}">
  <a>{{n}}</a>
 </li>

 select(item) {
      this.selected = item; 
  };
  isActive(item) {
      return this.selected === item;
  };
Run Code Online (Sandbox Code Playgroud)

只使用html

<li *ngFor="let n of list" [class.active]="clicked === n" 
         (click)="clicked = n">
       <a>{{n}}</a>
    </li>
Run Code Online (Sandbox Code Playgroud)

单击添加类,如果单击相同,则删除

select(item) {
   this.selected = (this.selected === item ? null : item); 
};
Run Code Online (Sandbox Code Playgroud)

只使用html

<li *ngFor="let n of list" [class.active]="clicked === n" 
       (click)="clicked = (clicked === n ? null :n)">
     <a>{{n}}</a>
   </li>
Run Code Online (Sandbox Code Playgroud)

更多信息