Apply a directive conditionally

前端 未结 15 1940
别跟我提以往
别跟我提以往 2020-11-27 15:11

I am using Material 2 to add md-raised-button. I want to apply this directive only if certain condition becomes true.

For example:

<         


        
15条回答
  •  难免孤独
    2020-11-27 15:49

    I am working with Angular Material, adding an element on *ngIf didn't work properly for me (the element would disappear inside many newly generated material HTML tags lol).

    I don't know if it's a good practice, but I used OnChanges and I had a sort of conditional directive - and it worked! :)

    So this is how I solved it:

    import { Directive, Renderer2, ElementRef, Input, OnChanges, SimpleChanges, AfterViewInit } from '@angular/core';
    
    @Directive({
      selector: '[appDirtyInputIndicator]'
    })
    export class DirtyInputIndicatorDirective implements OnChanges, AfterViewInit {
    
      @Input('appDirtyInputIndicator') dirtyInputIndicator: boolean;
      span = this.renderer.createElement('span');
    
      constructor(private renderer: Renderer2, private el: ElementRef) {}
    
      ngOnChanges(changes: SimpleChanges): void {
        if (changes.dirtyInputIndicator && this.dirtyInputIndicator) {
          this.renderer.appendChild(this.el.nativeElement, this.span);
        } else {
          this.renderer.removeChild(this.el.nativeElement, this.span);
        }
      }
    
      ngAfterViewInit() {
        this.renderer.addClass(this.span, 'dirty_input_badge');
      }
    }
    

提交回复
热议问题