0

I am trying to use angular Renderer2 to add and remove a class in HTML template. Here I am facing the difficulties:

  1. to add the class once component will load
  2. Only the selected item should have the class

I have created a demo in stackblitz. Please click here to see code.

Thank you.

<div class="tabs">
<a href="#" (click)="selectTab($event)">Tab 1 </a>
<a href="#" (click)="selectTab($event)">Tab 2 </a>
<a href="#" (click)="selectTab($event)">Tab 3</a>
</div>


constructor(private render:Renderer2){}
selectTab(event:any) {
this.render.addClass(event.target,"test");
}
4

1 回答 1

1

关于什么[ngClass]="{'test': selectedTab== 1}"

我创建了一个调用 selectedTab 的 ts 变量并声明为 number

在我使用过的 HTML 中[ngClass]="{'test': selectedTab== 1}",当 selectedTab = 1 时将添加测试类。

在单击方法上,我调用了 selectTab(2) 发送单击的选项卡参数并在 ts 中处理了此功能,例如

selectTab(selectedTab) {
if(selectedTab == 1){
  this.selectedTab = 1;
}else if(selectedTab == 2){
  this.selectedTab = 2;
}else{
  this.selectedTab = 3;
}  }
}
于 2019-01-13T06:17:07.503 回答