在angular2中实现addClass和removeClass功能 [英] implement addClass and removeClass functionality in angular2
本文介绍了在angular2中实现addClass和removeClass功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个用于ListView和GridView的按钮.为了在这两个按钮之间切换,我编写了如下的JQuery-
I have couple of buttons for ListView and GridView. For switching between these 2 buttons I had written JQuery like below-
<script type="text/javascript">
$(document).ready(function () {
$("button.switcher").bind("click", function (e) {
e.preventDefault();
var theid = $(this).attr("id");
var theitems = $("ul#items");
var classNames = $(this).attr('class').split(' ');
if ($(this).hasClass("active")) {
// if currently clicked button has the active class
// then we do nothing!
return false;
} else {
// otherwise we are clicking on the inactive button
// and in the process of switching views!
if (theid == "gridview") {
$(this).addClass("active");
$("#listview").removeClass("active");
// remove the list view and change to grid
theitems.removeClass("tilelist");
theitems.addClass("gridlist");
}
else if (theid == "listview") {
$(this).addClass("active");
$("#gridview").removeClass("active");
// remove the grid view and change to list
theitems.removeClass("gridlist")
theitems.addClass("tilelist");
}
}
});
});
</script>
现在,我想将此功能从Jquery移至Angular2打字稿应用程序.有人可以在这方面指导我吗?如何从angular2模板上单击按钮实现addClass和removeClass功能?
Now I want move this functionality from Jquery to Angular2 typescript application. Can anyone please guide me on this? How do I implement addClass and removeClass functionality on button click from angular2 template?
推荐答案
如果要在component.ts中使用它
If you want to due this in component.ts
HTML:
<button class="class1 class2" (click)="clicked($event)">Click me</button>
组件:
clicked(event) {
event.target.classList.add('class3'); // To ADD
event.target.classList.remove('class1'); // To Remove
event.target.classList.contains('class2'); // To check
event.target.classList.toggle('class4'); // To toggle
}
有关更多选项,示例和浏览器兼容性,请访问此链接.
For more options, examples and browser compatibility visit this link.
这篇关于在angular2中实现addClass和removeClass功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文