在angular2中实现addClass和removeClass功能

Gre*_*cks 22 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>
Run Code Online (Sandbox Code Playgroud)

现在我想将此功能从Jquery移动到Angular2 typescript应用程序.有人可以指导我吗?如何在angular2模板上点击按钮时实现addClass和removeClass功能?

Mal*_*zad 61

如果你想在component.ts中得到这个

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>
Run Code Online (Sandbox Code Playgroud)

零件:

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
}
Run Code Online (Sandbox Code Playgroud)

有关更多选项,示例和浏览器兼容性,请访问此链接.


Ang*_*hub 14

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

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


Gün*_*uer 7

为什么不使用

<div [ngClass]="classes"> </div>
Run Code Online (Sandbox Code Playgroud)

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

  • 对于单个类,还有`[class.someClass] ="someBooleanExpressino"`.http://angular.io有很多很棒的文档. (4认同)