2016-08-04 17 views
8

में addClass और removeClass कार्यक्षमता को लागू करें मेरे पास ListView और GridView के लिए कुछ बटन हैं। इन 2 बटन के बीच स्विच करने के लिए मैं की तरह below-कोणीय 2

<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> 

अब मैं Angular2 टाइपप्रति आवेदन करने के लिए Jquery से इस कार्यक्षमता ले जाना चाहते हैं JQuery लिखा था। क्या कोई मुझे इस पर मार्गदर्शन कर सकता है? मैं angular2 टेम्पलेट से बटन क्लिक पर addClass और removeClass कार्यक्षमता को कैसे कार्यान्वित करूं?

उत्तर

6

क्यों सिर्फ [ngClass] संपत्ति के माध्यम से इसका इस्तेमाल करने का उपयोग नहीं कर

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

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

+0

के लिए मैं इस बारे में पता नहीं था। इस विकल्प को आजमाएं। धन्यवाद :) –

+1

एकल वर्गों के लिए '[class.someClass] =" someBooleanExpressino "भी है। http://angular.io में बहुत सारे दस्तावेज़ हैं। –

9

प्रयास करें:

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

आप component.ts में इस वजह से चाहते हैं

एचटीएमएल :

<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.