【问题标题】:Directive in Angular 5 for return htmlAngular 5 中用于返回 html 的指令
【发布时间】:2023-03-20 01:21:01
【问题描述】:

如何按指令返回小 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 angular5 angular-directive


    【解决方案1】:

    你可以从@angular/core 使用ElementRef

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

    【讨论】:

    • 如何声明这个指令才能在 html 中使用&lt;app-icon glyph="music"&gt;&lt;app-icon&gt;
    • 好的,我已经知道了。你需要有:selector: "app-icon" - 没有括号[ ]
    • 使用 [appIcon] 选择器(camelCase 用于指令选择器),您可以将其添加到像这样的 div &lt;div appIcon&gt;&lt;/div&gt;
    【解决方案2】:

    根据之前的答案,我以这种方式解决了这个问题:

    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 未在构造函数中初始化

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 2018-08-14
      • 2018-09-02
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 2019-11-17
      相关资源
      最近更新 更多