Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append HTML tags or elements to a div in Angular 6?

Tags:

angular

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).

like image 994
Ali Avatar asked Jul 14 '18 16:07

Ali


2 Answers

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;
like image 84
Ali Avatar answered Oct 30 '22 09:10

Ali


 <div [innerHTML]="divMessages"></div>

in typescript you can append by this way

var appendElement = '<li>'+data.message+'</li>' ;
this.divMessages = appendElement;
like image 25
Mohit Avatar answered Oct 30 '22 09:10

Mohit