【问题标题】:Display [object HTMLElement] as HTML in Angular在 Angular 中将 [object HTMLElement] 显示为 HTML
【发布时间】:2020-12-06 19:29:20
【问题描述】:

我有一个指令,我正在尝试更改 HTML 对象的 innerHTML。

let icon: HTMLElement;
let attribute = document.createAttribute('icon');
icon = document.createElement('fa-icon');
attribute.value = "home";
icon.setAttributeNode(attribute);
 
this.elementRef.nativeElement.innerHTML = icon;

它确实有效,但是当我看到更改时,它总是显示 [object HTMLElement] 而不是应该是 fontAwesome 图标的 html。

我做错了什么,如何插入 icon 变量?

【问题讨论】:

  • 你没有开发 Angular 的方式。我们通常不会在 Angular 中进行这样的 DOM 操作,我们构建生成所需 DOM 元素的组件。如果你用你的用例扩展你的问题,我可能会解释你将如何构建一个你需要的组件。
  • 我使用的是 NGx-datatable 库,表格中填充了数值,如果后继值大于前一个值,我需要添加一个图标。我的大部分麻烦都来自使用这个库。
  • 看看我的库 ngx-ez 中的表格组件,它没有很好地记录,但传入模板很容易。 stackblitz.com/edit/…

标签: javascript html angular angular-directive


【解决方案1】:

通过this.elementRef.nativeElement.innerHTML = icon;,您实际上是将innerHTML 设置为元素对象,而不是将元素添加为子对象。您必须改为清除元素的innerHTML,然后在其上使用appendChild()

let icon: HTMLElement;
let attribute = document.createAttribute('icon');
icon = document.createElement('fa-icon');
attribute.value = 'home';
icon.setAttributeNode(attribute);
 
this.elementRef.nativeElement.innerHTML = ''; // Clear the innerHTML
this.elementRef.nativeElement.appendChild(icon); // Append the child

或者,如果您不需要对元素的引用来更改它,您实际上可以将元素的innerHTML 属性设置为iconouterHTML 属性。

let icon: HTMLElement;
let attribute = document.createAttribute('icon');
icon = document.createElement('fa-icon');
attribute.value = 'home';
icon.setAttributeNode(attribute);
 
this.elementRef.nativeElement.innerHTML = icon.outerHTML;

【讨论】:

  • 谢谢,但是在应用您的解决方案时,在检查器中,它显示 icon 变量现在已显示,但它现在什么也不显示。
  • @AndreGomez 我想不出为什么会发生这种情况。您是否尝试过这两种解决方案? (假设您不需要引用icon
【解决方案2】:

appendChild() 会有所帮助。

改变

this.elementRef.nativeElement.innerHTML = icon;

this.elementRef.nativeElement.appendChild(icon);

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多