Angular DomSanitizer 替换 textarea 字段上的换行符

Angular DomSanitizer replacing new line characters on textarea fields

提问人:the_overflowing_stack 提问时间:5/18/2023 最后编辑:the_overflowing_stack 更新时间:5/18/2023 访问量:132

问:

Angular 的 DomSanitizer 只是一个美化的文本替换器吗?如果是这样,我想知道实现我自己的清理程序是否可行,因为 Angular 正在将“<”等特殊字符替换为 ,而我认为它应该只用什么都替换“<”,因为看起来很恶心,而且它还替换了字段中的“\r\n”,而不仅仅是让我添加一个无害的新行字符。(仅供参考,使用 Angular 11。&lt;&lt;<textarea>&#10;

我正在尝试使用 Angular 的 DomSanitizer 作为这样的:

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>

我的.pipe.ts文件:


@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
    }
} 

输入字段也发生了同样的问题(显示相同的内容,而不仅仅是替换/阻止它们被添加/显示):&lt;

<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()
})

我尝试在管道中使用此替换代码,看看是否可以显示新行,但它只是在 textarea 字段中显示一个文字,而不是显示一个实际的新行。<br>

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
}
Angular 表单 textarea 清理 angular-dom-sanitizer

评论


答: 暂无答案