Search code examples
angularangular5angular-directive

Directive in Angular 5 for return html


How can I return small html piece by directive. This is what I am trying to do:

<app-icon glyph="music"><app-icon>

should be replaced by:

<span class='glyphicon glyphico-music' aria-hidden='true'></span>

And my wrong directive:

import { Directive } from "@angular/core";

@Directive({
  selector: "[app-icon]"
})
export class IconDirective {

  constructor(value: string) {
    return "<span class='glyphicon glyphicon-" +value + "' aria-hidden='true'></span>";
  }

}

Solution

  • Based on previous answer I solved that in that way:

    import { Directive, ElementRef, Input, OnInit } from "@angular/core";
    
    @Directive({
      selector: "app-icon"
    })
    export class IconDirective implements OnInit {
      @Input() glyph;
    
      constructor(private el: ElementRef) { }
    
      ngOnInit() {
        this.el.nativeElement.insertAdjacentHTML("beforeend",
          `<span class='glyphicon glyphicon-${this.glyph} aria-hidden='true'></span>`);
      }
    
    }
    

    ngOnInit is required because @Input glyph is not initialized in contstructor