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

前端 未结 2 2076
无人及你
无人及你 2020-12-18 08:09

I have a div in a template that has #divMessages as a template reference name.

When some events occu

2条回答
  •  温柔的废话
    2020-12-18 08:37

    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;
    

提交回复
热议问题