[typescript] implement addClass and removeClass functionality in angular2

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>

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?

This question is related to typescript angular

The answer is


Why not just using

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

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


Try to use it via [ngClass] property:

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

You can basically switch the class using [ngClass]

for example

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

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

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.


Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7