Search code examples
javascripthtmlangularangular-directive

Display [object HTMLElement] as HTML in Angular


I have a directive, and I am trying to change the innerHTML of an HTMLobject.

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

It does work, but when I see the changes it always displays [object HTMLElement] instead of the html that should be a fontAwesome icon.

What am I doing wrong and how would I insert the icon variable?


Solution

  • By doing this.elementRef.nativeElement.innerHTML = icon;, you are actually setting the innerHTML to the element object instead of adding the element as a child. You have to instead clear the innerHTML of the element and then use appendChild() on it.

    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
    

    Alternatively, if you don't need a reference to the element to be able to change it, you can actually just set the innerHTML property of the element to the outerHTML property of icon.

    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;