I have a div in a template that has #divMessages as a template reference name.
<div #divMessages></div>
When some events occur, I want to append HTML tags to this div. I tried in the following way but HTML tags appended as a string.
this.divMessages.nativeElement.append('<li>'+data.message+ '</li>');
My current method considers HTML tags as a string. How I can append HTML tags, to hide the tags and show only the data. (means only list items are shown and the tags are hidden in the above case).
I solved this problem by using the Renderer2 Abstract class, Which is a service provided by Angular to Manipulate DOM elements. Import the Renderer2 from angular core. then create element and append text to it.
import {Component, OnInit,NgModule, Renderer2 } from '@angular/core';
pass Renderer2 object to class constructur.
constructor(private http: HttpClient,private renderer:Renderer2) { }
//create the DOM element
let li=this.renderer.createElement('li');
//create text for the element
const text = this.renderer.createText(data.message);
//append text to li element
this.renderer.appendChild(li, text);
//Now append the li tag to divMessages div
this.renderer.appendChild(this.divMessages.nativeElement,li);
i used @ViewChild decorator to get the div as a divMessages
@ViewChild("divMessages", {read: ElementRef}) private divMessages: ElementRef;
<div [innerHTML]="divMessages"></div>
in typescript you can append by this way
var appendElement = '<li>'+data.message+'</li>' ;
this.divMessages = appendElement;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With