在 angular2 中实现 addClass 和 removeClass 功能

新手上路,请多包涵

我有几个用于 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 许可协议

阅读 468
1 个回答

在 Angular 13+ 中,我使用以下更新获得了 Malik 的代码:

零件:

 clicked(event: any) {
    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
  }

原文由 user11913484 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进