Angular2 provides innerHTML directive set HTML to div. By using this directive we can append and prepend HTML to div. You can download the below example source code from github

Markup

Observe below markup. The html content in myHtml variable will be the HTML content of the div
<button (click)="append()">Append</button>
<button (click)="prepend()">Prepend</button>
<div [innerHTML]="myHtml"></div>

Script - app.component.ts

Observe below component code. append and prepend functions append HTML and prepend HTML to div respectively
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `
  <h2>Append or Prepend HTML to div</h2>
  <div>
    <button (click)="append()">Append</button>
    <button (click)="prepend()">Prepend</button>
  </div><br/><br/>
  <div [innerHTML]="myHtml"></div>
  `
})
export class AppComponent {
  myHtml: string = '<div><i>basic initial HTML</i></div>';
  appendedHtml: string = '<div><b>this appended html</b></div>';
  prenpendHtml: string = '<div><b>this prepended html</b></div>';

  append(): void {
    this.myHtml = this.myHtml + this.appendedHtml;
  }

  prepend(): void {
    this.myHtml = this.prenpendHtml + this.myHtml;
  }

}

0 comments:

Blogroll

Popular Posts