How to add/remove class from directive

后端 未结 4 716
误落风尘
误落风尘 2020-12-16 15:16

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

Example:



        
4条回答
  •  一个人的身影
    2020-12-16 15:37

    export class CustomDirective {
       classname:string = "magenta";
    
       constructor(private renderer: Renderer2,
                   private elementRef: ElementRef,
                   service: SomService) {
       }
    
       addClass(className: string, element: any) {
            // make sure you declare classname in your main style.css
            this.renderer.addClass(this.elementRef.nativeElement, className);
       }
    
       removeClass(className: string, element: any) {
           this.renderer.removeClass(this.elementRef.nativeElement,className);
       }
    
    }
    

提交回复
热议问题