3

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...

1
  • I have deleted wrong part Commented Apr 25, 2019 at 11:24

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

where is my ngModel product.label etc. its like hello is hardcoded. ? And there is syntax error in there about saint:Domsanitizer is not used
and I want to prevent html script entering not allowing html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.