DOM sanitize function is not escaping the text that user entered

Viewed 33

Was trying to use Angular Sanitize API with the user input entered by the user inside angular form. But the Angular's Sanitize() is not escaping the input entered.

.ts

export class AppComponent {
  userName = 'Angular';

  constructor(private domSanitizer: DomSanitizer) {}

  onSave(): void {
    console.log('save clicked api call');
    this.sanitizeUserName();
  }

  sanitizeUserName(): string {
    const domSanitize = this.domSanitizer.sanitize(1, this.userName);
    console.log('sanitized text/html', domSanitize);
    return domSanitize;
  }
}

.html

<form #userForm="ngForm">
  <label>Username: </label>
  <input type="text" [(ngModel)]="userName" name="username" />

  <div>
    <span>View : </span>
    <div [innerHTML]="userName"></div>
  </div>

  <br />
  <br />
  <button type="button" (click)="onSave()">Save</button>
</form>

Please find the live example here. In component.ts I have added few examples to verify if the input sanitization.

If someone can help me out.

1 Answers

sanitize method models is:

 sanitize(context: SecurityContext, value: SafeValue | string | null): string | null;

and the SecurityContext model is:

enum SecurityContext {
    NONE = 0,
    HTML = 1,
    STYLE = 2,
    SCRIPT = 3,
    URL = 4,
    RESOURCE_URL = 5
}

So it seems that you should use the number one for SecurityContext

  sanitizeUserName(): string {
    const domSanitize = this.domSanitizer.sanitize(1, this.userName);
    console.log('sanitized text/html', domSanitize);
    return domSanitize;
  }
Related