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 :-
- sanitize()
- bypassSecurityTrustHtml()
- bypassSecurityTrustStyle()
- bypassSecurityTrustScript()
- bypassSecurityTrustUrl()
- 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' @Component({ 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"> </div> </div> <button class="btn btn-dark mx-2" (click)="submit()">submit</button> </div> ` 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> </section>
Now, run your angular application using npm start
Output :