Angular2 is proving and ngClass directive as like Angular1. We can manipulate classes using this ngClass

Steps to add class using ngClass : 

  1. Initiate this.myClass to array
  2. Push classes into above array
this.myClass = [];
this.myClass.push('red');

Steps to remove class using ngClass : 

  1. Initiate $scope.myClass to array
  2. Pop classes from above array
this.myClass = [];
this.myClass.pop('red');

Steps to check class using ngClass : 

  1. Initiate this.myClass to array
  2. Check index of the class that you want to check
this.myClass = ['red'];
if(this.myClass.indexOf('red') == -1) {
    alert('false');
} else {
    alert('true');
}

Code for ngClass with Array

(function(app) {
  
  app.AppComponent = ng.core
    .Component({
      selector: 'my-app',
      templateUrl: 'ngClass_template.html'
    })
    .Class({
      constructor: function() {
        this.myClass = [];
      },
      
      addClass:function() {
        this.myClass.push('red');
      },
      
      removeClass:function() {
        this.myClass.pop('red');
      },
      
      checkClass:function() {
        if(this.myClass.indexOf('red') == -1) {
           alert('false');
        } else {
           alert('true');
        }
      }
    });

  
  document.addEventListener('DOMContentLoaded', function() {
    ng.platform.browser.bootstrap(app.AppComponent);
  });

})(window.app || (window.app = {}));
View DEMO

Steps to add class using ngClass with JSON

  1. Initiate this.myClass to JSON object of classes and boolean values
  2. Assign true for the JSON class name, that you want to add
this.myClass = {red:false};
addClass : function() {
   this.myClass.red = true;
}

Steps to remove class using ngClass with JSON

  1. Initiate $scope.myClass to JSON object of classes and boolean values
  2. Assign false for the JSON class name, that you want to remove
this.myClass = {red:false};
removeClass : function() {
    this.myClass.red = false;
}

Steps to toggle class using ngClass with JSON

  1. Initiate $scope.myClass to JSON object of classes and boolean values
  2. Assign opposite boolean value to the JSON class name
this.myClass = {red:false};
toggleClass : function() {
     this.myClass.red = !this.myClass.red;
};

Code for ngClass with JSON

(function(app) {
  
  app.AppComponent = ng.core
    .Component({
      selector: 'my-app',
      templateUrl: 'ngClass_template1.html'
    })
    .Class({
      constructor: function() {
          this.myClass = {red:false};
      },
      
      addClass:function() {
          this.myClass.red = true;
      },
      
      removeClass:function() {
          this.myClass.red = false;
      },
      
      toggleClass:function() {
          this.myClass.red = !this.myClass.red;
      },
      
      checkClass:function() {
          alert(this.myClass.red);
      }
    });
  
  
  
  document.addEventListener('DOMContentLoaded', function() {
    ng.platform.browser.bootstrap(app.AppComponent);
  });
})(window.app || (window.app = {}));
View DEMO

By Using [Class.]

Angular 2 is providing one way binding for classes with [class.<class name>]. It binds the presence of the CSS class red on the element to the truthiness of the expression redClassBool. Observe the below code
<div id="divID" [class.red]="redClassBool">
  This text color can be changed by class
</div>

Add Class

Assign true to this.redClassBool

Remove Class

Assign  false to this.redClassBool

Code for [class.] binding

(function(app) {
  
  app.AppComponent = ng.core
    .Component({
      selector: 'my-app',
      templateUrl: 'withCssClass_template1.html'
    })
    .Class({
      constructor: function() {
        this.redClassBool = false;
      },
      
      addClass:function() {
        this.redClassBool = true;
      },
      
      removeClass:function() {
        this.redClassBool = false;
      },
      
      toggleClass:function() {
        this.redClassBool = !this.redClassBool;
      },
      
      checkClass:function() {
        alert(this.redClassBool);
      }
    });
  
  
  
  document.addEventListener('DOMContentLoaded', function() {
    ng.platform.browser.bootstrap(app.AppComponent);
  });
})(window.app || (window.app = {}));
View DEMO

29 comments:

  1. Hi,

    Nice blog for adding / removing css

    I need help on css in angular2

    I have 3 links in the html and 3 links has some classes already and on top of that I need to

    add 1 more class when I click on the particular anchor element i.e active element.

    can you please help me on this.

    ReplyDelete
    Replies
    1. Hello, I know it has been month till you write. I did this to solve that issue, maybe it helps someone:

      import {Component, ViewChild, ElementRef } from '@angular/core';

      @Component({
      selector: 'my-app',
      template: '< div id="navbar" class="one two three" #navEle>'
      })

      export class AppComponent {
      @ViewChild('navEle') navBar :ElementRef;

      toggleNavbar() {
      let oldClass :string = this.navBar.nativeElement.className;
      this.navBar.nativeElement.className = oldClass.replace("three", "");
      }
      }

      Delete
    2. If someone didn't understand. I delete one class from the actual div, you could also add one. It's just a string object, you can replace, split, add etc. as you wish.

      Delete
    3. You can check this link
      http://www.angulartutorial.net/2017/04/add-class-to-active-element-angular-2.html

      Delete
    4. YouTube Music MOD APK

      YouTube Music MOD APK is a music player that lets you enjoy the countless music available on YouTube. This application offers a lot of useful features, including a playlist feature, which lets you add your favorite songs. The application is very easy to use and you can enjoy it in complete silence. Besides, it supports back-to-back play. If you want to try out YouTube, make sure that your device meets minimum system requirements.

      YouTube Music mod apk is the perfect tool for those who love listening to music. Its database is almost identical to that of YouTube, so you'll find most music-related content in the search bar. There are also a lot of exciting features that you can enjoy with this application. If you'd like to get all the benefits of this app without paying any extra money, you can download the premium version of YouTube Music.

      In addition to being a powerful music player, YouTube Music also lets you hide and flag inappropriate content. These features make the service far more enjoyable and accessible to users, ensuring that everyone can enjoy music. Normally, the premium version of YouTube can cost you money, but the premium version can be downloaded for free. If you want to try out premium versions of YouTube Music, download the premium mod. This app is a great way to get the latest music without paying anything.

      Apart from being free, YouTube Music Mod APK also allows you to download songs to listen to them on the go. You can use it offline to listen to them at a later time. It's best to follow the instructions carefully and ensure that you don't do anything to break the app's compatibility. This is an excellent way to enjoy music without paying money. With this app, you'll be able to find the best songs without spending any money.

      Another great feature of YouTube Music MOD APK is the ability to download songs. This enables you to listen to music without using data. You can also search for a song by line or lyrics. This is the most convenient way to enjoy your favorite songs. If you're a frequent listener of YouTube, this app will make your experience even better. You won't be interrupted with ads, so you can enjoy your music without distractions.

      Using YouTube Music MOD APK is a great way to listen to music offline. It allows you to download and listen to songs without the need for an internet connection. Moreover, it also offers many features to make your experience on YouTube more pleasurable. With this application, you'll be able to download and play millions of songs. And while you're downloading them, you'll also be rewarded with a variety of other premium features.

      Delete
  2. your article is very good and very helpful. every one can use and know that how Creating Custom Animations for Use in Tableau. if you want to gif covert to image than check it you can easily understand that how to Use GIF Converter to Get Images for Marketing

    ReplyDelete
  3. Really informative article.Really looking forward to read more. Really Cool.
    เว็บไซต์คาสิโนออนไลน์ที่ได้คุณภาพอับดับ 1 ของประเทศ
    เป็นเว็บไซต์การพนันออนไลน์ที่มีคนมา Gclub Royal1688
    และยังมีหวยให้คุณได้เล่น สมัครหวยออนไลน์ ได้เลย
    สมัครสล็อตออนไลน์ได้ที่นี่ >>> Golden slot
    ร่วมลงทุนสมัครเอเย่น Gclubกับทีมงานของเราได้เลย

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete

  5. Im grateful for the blog post.Really thank you!โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร Gclub กับทางทีมงานของเราเพียงเท่านั้น
    ร่วมมาเป็นส่วนหนึ่งกับเว็บไซต์คาสิโนออนไลน์ของเราได้เลยค่ะ
    สมัครสล็อตออนไลน์ >>> goldenslot
    สนใจร่วมลงทุนกับเรา สมัครเอเย่น Gclub คลิ๊กได้เลย

    ReplyDelete
  6. Good News received from the ( COC MOD and GBWhatsapp ) ... This are the only sites that offers us all the latest updated WhatsApp Alternatives.. We can use this WhatsApp on our phone for our primary and secondary WhatsApp numbers...I thought it will be useful for us..That's why I shared it with all of us...Thank you

    ReplyDelete
  7. Thank You, Also Check Our Recent Post On Free Forex Signals

    ReplyDelete
  8. Thanks for the detailed article on this topic. I would like to see more such awesome articles from you. Download GBWhatsApp APK

    ReplyDelete
  9. Have you ever tried COC MOD Apk, which is the Mod version of its original server.

    ReplyDelete
  10. Thanks for the detailed article on this topic. I would like to see more such awesome articles from you. Also you can get the new and best features of GBWhatsapp which are coming in 2022- GBWhatsapp 2022 APK

    ReplyDelete
  11. Thank you for sharing this. It was helpful. Keep sharing such things.
    Also I like to play Nulls Brawl Apk which is more fun than any other game.

    ReplyDelete
  12. Market Live Rates Lets You Find The Best Brokers And Strategies For Your Online Trading. In-depth Broker Reviews And Login Details. Get Investment Recommendations From The Experts.

    ReplyDelete
  13. Track your stocks in all major markets instantly with our unique live stock overview. See Ftoc Stock live prices changes as they occur and view change details, including volume and share changes.

    ReplyDelete
  14. I was looking for another article by chance and found your article 룰렛 I am writing on this topic, so I think it will help a lot. I leave my blog address below. Please visit once.

    ReplyDelete
  15. Hello.This post was extremely interesting, particularly because I was looking for thoughts on this topic last Thursday. Regards GBWhatsapp APK

    ReplyDelete
  16. If you want a duplicate lesco wapda bill Check online without any issue so must visit this lesco wapda bill check online

    ReplyDelete
  17. If you are looking for the best hp laptop under 20000 in Pakistan so you must visit this link Best hp Laptop Under 20000

    ReplyDelete
  18. Do you want to consult about your company's cloud services, contact 0 scale as 0scale is an AWS Premier Consulting Partner with 11 AWS expertise that offers in-depth technical skills to enable organizations to modernize on the cloud. We are skilled at designing, executing, optimizing, and handling customized cloud solutions on AWS that coerce the innovation our clients require to achieve their business transformation initiatives. 0scale

    ReplyDelete

Blogroll

Popular Posts