在Angular中将[object HTMLElement]显示为HTML

问题描述

我有一条指令,我正在尝试更改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。

我在做什么错,我该如何插入图标变量?

解决方法

通过执行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属性设置为{{1 }}。

outerHTML
,

appendChild()会有所帮助。

更改

this.elementRef.nativeElement.innerHTML = icon;

this.elementRef.nativeElement.appendChild(icon);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...