How to add / remove a class from a directive

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

Example:

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

    if (service.someCondition()) {
        // code to remove class
    }
  }
}
+7
source share
3 answers

If you do not want to use the directive ngClass(hint: you can pass a function [ngClass]="myClasses()"if it is randomly built into your template), you can just use Renderer2one or more classes for it:

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);
   }

}
+23
source
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);
   }

}
0
source

Angular, @HostBinding class.your-class, / . DI Renderer2 / .

, Bootstrap Reactive Forms , - :

import { Directive, Self, HostBinding, Input } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[appCheckFormFieldValidity]'
})
export class CheckFormFieldValidity{
  @Input() public class: string;

  constructor(
    @Self() private ngControl: NgControl
  ) { }

  @HostBinding('class.is-valid')
  public get isValid(): boolean {
    return this.valid;
  }

  @HostBinding('class.is-invalid')
  public get isInvalid(): boolean {
    return this.invalid;
  }

  public get valid(): boolean {
    return this.ngControl.valid && 
    (this.ngControl.dirty || this.ngControl.touched);
  }

  public get invalid(): boolean {
    return !this.ngControl.pending &&
      !this.ngControl.valid &&
      (this.ngControl.touched || this.ngControl.dirty);
  }
}

, @HostBinding, StackBlitz

0

Source: https://habr.com/ru/post/1666081/


All Articles