Angular2 - Add div to DOM

14,223

You can bind html using the [innerHtml] tag. That way you don't need the viewchild.:

<div [innerHtml]="htmlText"></div>

Component:

export class BuilderComponent {

  htmlText: string;

  ngAfterViewInit() { }

  addRow() {

     this.htmlText = this.htmlText + `<div #row class="row">
       <div class="s12 teal lighten-2">
        <p class="flow-text">div inside parent - html builder</p>
      </div>
    </div>`;
  }
}

Another solution i would properly use is to create an array of strings, and use *ngFor and a template to loop through it. By doing so it's possible to avoid HTML in typescript, and you don't need to edit the html both places each time there's an update.

For example:

Template:

<div *ngFor="let row of rows" class="row">
  <div class="s12 teal lighten-2">
    <p class="flow-text">{{ row }}</p>
  </div>
</div>

Component:

export class BuilderComponent {

  rows: Array<string> = new Array();

  ngAfterViewInit() { }

  addRow() {
    this.rows.push("Test 123 text");
  }
}
Share:
14,223
Marrone
Author by

Marrone

Updated on June 21, 2022

Comments

  • Marrone
    Marrone almost 2 years

    I am trying to add some child elements to a div using Angular2. I know I can get the element using @ViewChild but how can I actually append some html code into the DOM?

    What I'm trying to do is "mimic" the JQuery append function. Is there any way to do that in Angular2 ?

    Thanks very much for the help!

    Here is my component:

    import { Component, ViewChild, ElementRef } from '@angular/core';
    
    @Component({
    
      moduleId: module.id,
    
      selector: 'my-selector',
    
      template: `<div #builder class="row">
      <div class="s12 teal lighten-2">
        <p class="flow-text">teste do html builder</p>
      </div>
    </div>
    <a class="btn-floating btn-large waves-effect waves-light red"    (click)="addRow()"><i class="material-icons">add</i></a>`,
    
    })
    
    export class BuilderComponent {
    
    @ViewChild('builder') builder:ElementRef;
    
      ngAfterViewInit() {
        console.log(this.builder.nativeElement.innerHTML);
      }
    
      addRow() {
    
         let htmlText = `<div #row class="row">
           <div class="s12 teal lighten-2">
            <p class="flow-text">div inside parent - html builder</p>
          </div>
        </div>`;
    
         this.builder.nativeElement.append(htmlText); (???)
      }
     }