如何从指令添加/删除类 [英] How to add/remove class from directive

查看:80
本文介绍了如何从指令添加/删除类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用自定义指令如何根据特定条件在主机元素上添加/删除类?

Using a custom directive how would you add/remove a class on the host element based on a specific conditions?

示例:

@Directive({
  selector: '[customDirective]'
})
export class CustomDirective {
  constructor(service: SomService) {
    // code to add class

    if (service.someCondition()) {
        // code to remove class
    }
  }
}

推荐答案

如果您不想使用ngClass指令(提示:如果要在[ngClass]="myClasses()"中进行杂乱的内联,则可以将函数传递给[ngClass]="myClasses()"您的模板),您只需利用Renderer2为其添加一个或多个类:

If you don't want to use the ngClass directive (Hint: you can pass a function to [ngClass]="myClasses()" if it would be to messy inline in your template) you can just utilize the Renderer2 for it to add one or more classes:

export class CustomDirective {

   constructor(private renderer: Renderer2,
               private elementRef: ElementRef,
               service: SomService) {
   }

   addClass(className: string, element: any) {
       this.renderer.addClass(element, className);
       // or use the host element directly
       // this.renderer.addClass(this.elementRef.nativeElement, className);
   }

   removeClass(className: string, element: any) {
       this.renderer.removeClass(element, className);
   }

}

这篇关于如何从指令添加/删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆