我有几个用于 ListView 和 GridView 的按钮。为了在这两个按钮之间切换,我编写了如下的 JQuery-
<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 功能?
原文由 Gretel Hendricks 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 Angular 13+ 中,我使用以下更新获得了 Malik 的代码:
零件: