问题描述
我有一条指令,我正在尝试更改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);