You can display Angular variable in double curly braces - {{variable}}.  Whatever variable in these double curly braces, will be displayed as text. Angular 2 provides innerHTML directive, which set HTML to the element.

Markup  

Observe below markup. myHtml value displayed as both HTML and text
<div [innerHTML]="myHtml"></div>
<div>{{myHtml}}</div>

Script - app.component.ts

Observe below code, setText(), setHtml() functions set Html and Text data. You can view the result through the template.
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `
  <h2>Set Text or HTML to div</h2>
  <div>
    <button (click)="setText()">Set Text</button>
    <button (click)="setHtml()">Set HTML</button>
  </div><br/><br/>
  <div [innerHTML]="myHtml"></div>
  <div>{{myHtml}}</div>
  `
})
export class AppComponent {
  myHtml: string = '<div><i>basic initial HTML</i></div>';
  text: string = 'this is sample text';
  html: string = '<div><b>this is sample html</b></div>';

  setText(): void {
    this.myHtml = this.text;
  }

  setHtml(): void {
    this.myHtml = this.html;
  }
}

0 comments:

Blogroll

Follow this blog by Email

Popular Posts