Chris Garsonn
Chris Garsonn

Reputation: 777

How to prevent html injection in Angular 5

I want to prevent users to enter html injection to textbox. I have researched some example but they are generally about allowing html tags through pipes and saying angular automatically sanitizes html tags. But in my example when I enter <script>alert('blabla')</script> to text box, it is accepted and registered to db like this..

How can I prevent it ?

My template code is:

<div fxLayout="row">
          <mat-form-field fxFlex="20">
            <input matInput name="label" [(ngModel)]="product.label" placeholder="Label"
                   required>
          </mat-form-field>
        </div>

and my ts file is:

import { Product } from '../../../';

@Component({
  selector: '....',
  templateUrl: '....',
  styleUrls: ['....']
})
export class ProductEditComponent implements OnInit {

  product: Product = <Product>{};

  constructor(some services etc.) {

  }

  ngOnInit() {

   //some code
  }

Note again: I want to prevent entering html script injection, not allowing it with bypass or pipe...

Upvotes: 2

Views: 7149

Answers (1)

onik
onik

Reputation: 1631

you could use DomSanitizer for that

import { DomSanitizer } from "@angular/platform-browser"
import { SecurityContext } from "@angular/core";

constructor(private sanit:DomSanitizer){
  var dom = this.sanitizer.sanitize(SecurityContext.HTML, "<script> alert('HELLO'); </script>");
  console.log(dom);
}

if it returns null, then it was an issue with html,else it returns passed html

Upvotes: 3

Related Questions