Angular raw html binding |innerHtml example


This tutorials solves the below problems in html binding Angular application

  • How to do string raw html binding in Angular?
  • Render html strings with html tags
  • How innerHtml attribute in Angular works?
  • How to sanitize html tag content with DomSanitizer
  • innerhtml change event handler exam

In Angular, It is simple to bind the properties and events using two way binding syntax.

Property binding can be done using below syntax

[property]="javascriptexpression"

Event binding syntax as seen below

(event)="javascriptexpression"

Property and event binding i.e two way binding syntax is

[(ngModel)]="property"

JavaScript expression are either values and properties from json object, JavaScript functions

Suppose, Sometimes we want to bind the HTML response instead of JSON response.

How html binding works in Angular application

using innerHtml attribute binding, We can bind html content in the form of string

innerHtml attribute can be added to html tag with below two ways

Syntax:

<div [innerHTML]="variable"></div>
<div innerHTML="{{variable}}"></div>

Here is a typescript component

Created variable content to hold html tag string

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  content: string;
  constructor() {
    this.content = "<i>html response</i>";
  }
}

Here is html component

Angular treat innerHtml content as unsafe, so it do sanitize automatically

<h3>
  Angular html binding Innerhtml example
</h3>
<span [innerHtml]="content"></span>

As the raw html content is passed to angular component, We have to check html is trusted or not.

Then, How to sanitize raw html Angular manually?

  • imported DomSanitizer in angular component
  • declared variable content of type SafeHtml
  • Pass the content bypassSecurityTrustHtml and return trusted and safe html string content
import { Component } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  content: SafeHtml;
  constructor(private sanitizer: DomSanitizer) {
    this.content = this.sanitizer.bypassSecurityTrustHtml(
      "<i>html response</i>"
    );
  }
}

Change event handler inside html content string using innerHtml

html tag string content contains events as part of a content, Then how do you initite a click event bind handler.

In Angular event listeners are attached to handlers once content is loaded.

ngAfterViewChecked call method used which is a call back method running whenever change detection

In this below example, button defination is displyaed using innerHtml

Once button is rendered, We are adding click event binding to button inside ngAfterViewChecked method ElementRef QuerySelector method is used to select the DOM Button using id

Here is an complete example for event listener for innerHtml

import { Component, ElementRef } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  content: SafeHtml;

  constructor(private elementRef: ElementRef, private sanitizer: DomSanitizer) {
    this.content = this.sanitizer.bypassSecurityTrustHtml(
      '<button type="button" id="submitButton" (click)="openWindow()">Submit</buttn>'
    );
  }
  openWindow() {
    alert("Welcome");
  }
  ngAfterViewChecked() {
    if (this.elementRef.nativeElement.querySelector("#submitButton")) {
      this.elementRef.nativeElement
        .querySelector("#submitButton")
        .addEventListener("click", this.openWindow.bind(this));
    }
  }
}

Stackblitz code

You can find the code for this tutorial

Conclusion

to sum up, Angular innerHtml attributes provides dynamic binding of html string content and also using ngAfterViewChecked, we can bind the event listeners

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Angular Material list | Best mat-list and item examples

Fix for Property has no initializer and is not definitely assigned in the constructor

How to convert json to/from  object in angular|Typescript 

Angular ngFor index - How to get current last even and odd index?

How to convert number to words in Angular|Typescript example

How to Format array of dates in typescript Angular example

In this post, you learn writing comments in Angular and typescript. You can also write single multiline and documentation comments in Typescript. This includes declare comments in Angular typescript and template HTML components.