5

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

3
  • Possibly similar question: stackoverflow.com/questions/43682801/… Commented Jul 14, 2018 at 16:58
  • thanks man, it seems i did't crawl the stackoverflow completely. Commented Jul 14, 2018 at 17:03
  • Just use an ngFor in your div, iterating over an array pf data, and add data to the array. If you're doing DOM manipulation i Angular, you're doing it wrong. You modify the model, and the view is updated automatically. Commented Jul 14, 2018 at 18:08

2 Answers 2

15

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;
Sign up to request clarification or add additional context in comments.

Comments

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

in typescript you can append by this way

var appendElement = '<li>'+data.message+'</li>' ;
this.divMessages = appendElement;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.