在angular2中实现addClass和removeClass功能

时间:2016-08-04 17:39:36

标签: typescript angular

我有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 typescript应用程序。有人可以指导我吗?如何在angular2模板按钮上实现addClass和removeClass功能?

4 个答案:

答案 0 :(得分:54)

如果你想在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
}

有关更多选项,示例和浏览器兼容性visit this link.

答案 1 :(得分:13)

尝试通过[ngClass]属性使用它:

<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
         (click)="toggle(!isOn)">
         Click me!
     </div>`,

答案 2 :(得分:7)

为什么不使用

<div [ngClass]="classes"> </div>

https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

答案 3 :(得分:0)

您基本上可以使用[ngClass]切换类

例如

<button [ngClass]="{'active': selectedItem === 'item1'}" (click)="selectedItem = 'item1'">Button One</button>
<button [ngClass]="{'active': selectedItem === 'item2'}" (click)="selectedItem = 'item2'">Button Two</button>