Angular2 - Add div to DOM

I am trying to add some children to a div using Angular2. I know I can get the element using @ViewChild, but how can I add some HTML in the DOM?

What I'm trying to do is "mimic" the jQuery add function. Is there a way to do this in Angular2?

Many thanks 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); (???) } } 
+6
source share
1 answer

You can link the html using the [innerHtml] tag. This way you do not need a 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 that I would use correctly is to create an array of strings and use * ngFor and a pattern to scroll through it. By doing so, you can avoid HTML in typescript, and you don't need to edit html both places with every update.

For instance:

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"); } } 
+10
source

All Articles