Angular ngClass and click event for toggling class

2019-02-03 07:15发布

In Angular, I would like to use ngClass and click event to toggle class. I looked through online but some are angular1 and there isn't any clear instruction or example. Any help will be much appreciated!

In HTML, I have the following:

<div class="my_class" (click)="clickEvent($event)"  ngClass="{'active': toggle}">                
     Some content
</div>

In .ts:

 clickEvent(event){
    //Haven't really got far
    var targetEle = event.srcElement.attributes.class;        
 }     

5条回答
乱世女痞
2楼-- · 2019-02-03 07:47

Angular6 using the renderer2 without any variables and a clean template:

template:

<div (click)="toggleClass($event,'testClass')"></div>

in ts:

toggleClass(event: any, class: string) {
  const hasClass = event.target.classList.contains(class);

  if(hasClass) {
    this.renderer.removeClass(event.target, class);
  } else {
    this.renderer.addClass(event.target, class);
  }
}

One could put this in a directive too ;)

查看更多
Melony?
3楼-- · 2019-02-03 07:49

If you want to toggle text with a toggle button.

HTMLfile which is using bootstrap:

<input class="btn" (click)="muteStream()"  type="button"
          [ngClass]="status ? 'btn-success' : 'btn-danger'" 
          [value]="status ? 'unmute' : 'mute'"/>

TS file:

muteStream() {
   this.status = !this.status;
}
查看更多
趁早两清
4楼-- · 2019-02-03 07:59

This Should work for you:

<div class="my_class" (click)="clickEvent()"  
    [ngClass]="status ? 'success' : 'danger'">                
     Some content
</div>

status: boolean = false;
clickEvent(){
    this.status = !this.status;       
}
查看更多
Summer. ? 凉城
5楼-- · 2019-02-03 07:59

Instead of having to create a function in the ts file you can toggle a variable from the template itself. You can then use the variable to apply a specific class to the element. Like so-

<div (click)="status=!status"  
    [ngClass]="status ? 'success' : 'danger'">                
     Some content
</div>

So when status is true the class success is applied. When it is false danger class is applied.

This will work without any additional code in the ts file.

查看更多
别忘想泡老子
6楼-- · 2019-02-03 08:07

ngClass should be wrapped in square brackets as this is a property binding. Try this:

<div class="my_class" (click)="clickEvent($event)"  [ngClass]="{'active': toggle}">                
     Some content
</div>

In your component:

     //define the toogle property
     private toggle : boolean = false;

    //define your method
    clickEvent(event){
       //if you just want to toggle the class; change toggle variable.
       this.toggle != this.toggle;       
    }

Hope that helps.

查看更多
登录 后发表回答