How to add/remove class from directive

后端 未结 4 707
误落风尘
误落风尘 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:49

    When you are using directives in Angular you would want to use @HostBinding, and bind to class.your-class in order to be able to add/remove your class based on a predicate. You don't need to DI in the Renderer2 to effectively add/remove classes.

    For example, when using Bootstrap and Reactive Forms and you want to indicate a valid or invalid form field you can do something like:

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

    This is not a rigorous example, but it illustrates the use of @HostBinding, and I created the example in a StackBlitz

提交回复
热议问题