Apply a directive conditionally

前端 未结 15 1962
别跟我提以往
别跟我提以往 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:50

    I couldn't find a nice existing solution, so i built my own directive which does this.

    import { Directive, ElementRef, Input } from '@angular/core';
    
    @Directive({
      selector: '[dynamic-attr]'
    })
    export class DynamicAttrDirective {
      @Input('dynamic-attr') attr: string;
      private _el: ElementRef;
    
      constructor(el: ElementRef) {
        this._el = el;
      }
    
      ngOnInit() {
        if (this.attr === '') return null;
        const node = document.createAttribute(this.attr);
        this._el.nativeElement.setAttributeNode(node);
      }
    }
    

    Then your html:

提交回复
热议问题