0

Is Angular's DomSanitizer just a glorified text-replacer? If it is, I'd like to know if it's feasible to implement my own sanitizer, because the Angular one is replacing special characters like "<" with &lt;, when I think it should just replace "<" with nothing because &lt; is pretty gross to look at, and it's also replacing "\r\n" in <textarea> fields with &#10; instead of just letting me add a harmless new line character. (Using Angular 11 FYI.)

I'm attempting to use Angular's DomSanitizer as such:

TS:

comments: string = null;

constructor(public sanitizeHTML: SanitizeHtmlPipe) { }
...(irrelevant code)...

HTML:

<textarea class="form-control" [(ngModel)]="comments" name="comments" 
    [value]="comments | sanitizeHtml" 
    (change)="onCommentsChange()" (paste)="onCommentsChange()" 
    rows="7" required></textarea>

My .pipe.ts file:


@Pipe({
    name: 'sanitizeHTML'
})
export class SanitizeHtmlPipe implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) {
    }

    transform(potentiallyUnsafeHtml: string): SafeHtml {
        let sanitizedHtml = this.sanitizer.sanitize(SecurityContext.HTML, potentiallyUnsafeHtml);
        return sanitizedHtml
    }
} 

The same problem is happening on input fields (is showing the same &lt; stuff instead of just replacing / preventing them from being added / displayed):

<input formControlName="username" id="searchBox" 
    [value]="UsernameInputForm.get('username').value | sanitizeHTML"
    type="search" placeholder="Search User" 
    class="search-user">

(ts code: )
UsernameInputForm = new FormGroup({
    username: new FormControl()
})

I tried using this replacement code in the pipe to see if I could get new lines to display but it just shows a literal <br> in the textarea field instead of it displaying an actual new line.

transform(potentiallyUnsafeHtml: string): SafeHtml {
    let sanitizedHtml: any
    if(potentiallyUnsafeHtml != null) {
        potentiallyUnsafeHtml = potentiallyUnsafeHtml.replace(/<|>/g, '');
        potentiallyUnsafeHtml = potentiallyUnsafeHtml.replace(/(?:\r\n|\r|\n)/g, '<br>');
    }

    sanitizedHtml = this.sanitizer.sanitize(SecurityContext.HTML, potentiallyUnsafeHtml);
    // console.log("sanitizedHtml: ",sanitizedHtml)
    return sanitizedHtml
}

0 Answers0