Domsanitizer In Angular

Domsanitizer automatically removes the script element and keeps content safe. Dom-sanitizer will leave safe HTML intact, so in most situations this method should not be used.

Methods of  DomSanitizer :-

  1. sanitize()
  2. bypassSecurityTrustHtml()
  3. bypassSecurityTrustStyle()
  4. bypassSecurityTrustScript()
  5. bypassSecurityTrustUrl()
  6. bypassSecurityTrustResourceUrl()

Here, we are learn how to use domesanitizer in angular. First we need to inject Domsanitizer like below,

First, we are inject domsanitizer and add ts code in app.component.ts

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser'

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
export class AppComponent {

  dynamicArray: any

  constructor(private sanitizer: DomSanitizer) {


  addRow() {
    this.dynamicArray = `
    <div class="d-flex my-2">
      <div class="d-flex">
        <div class="w-100">
          <label>Name :</label>
          <input type="text">
          <label>Age :</label>
          <input type="number">
          <label>Contact NO :</label>
          <input type="number">
      <button class="btn btn-dark mx-2" (click)="submit()">submit</button>
    this.dynamicArray = this.sanitizer.bypassSecurityTrustHtml(this.dynamicArray)

    document.getElementsByClassName("row")[0].innerHTML += this.dynamicArray.changingThisBreaksApplicationSecurity


Here, we are add html code in app.component.html

<section class="m-5">
    <h2>Example Of Domsanitizer</h2>
  <button class="btn btn-dark" (click)="addRow()">Add Row</button>
  <div class="row"></div>

Now, run your angular application using npm start

Output :

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories