Angular 5 中的指令 return html

Directive in Angular 5 for return html

我如何return小html一块指令。这就是我想要做的:

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

应替换为:

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

我的错误指令:

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

}

您可以使用 @angular/core 中的 ElementRef :

 constructor(private _el: ElementRef) {
 this._el.nativeElement.insertAdjacentHTML('beforeend',
  '<span class='glyphicon glyphicon-" +value + "' aria-hidden='true'></span>');
 }

根据之前的回答我是这样解决的:

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 是必需的,因为 @Input glyph 未在构造函数

中初始化