You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Angular不对<img>和<b>标签进行转义?

Angular 13 输入HTML内容未被转义的解决方法

你的问题出在两个核心点:

  • 调用DomSanitizer.sanitize时用了数字1而非规范的SecurityContext枚举值
  • 仅调用了 sanitize 方法,但未将处理后的结果用于页面显示或覆盖原变量

问题拆解

  1. SecurityContext 枚举误用:代码里的1虽然对应SecurityContext.HTML,但直接写数字不规范且易出错,应该显式使用枚举常量。
  2. 未应用 sanitize 结果:页面的[innerHTML]绑定的是原始userName变量,而你调用sanitizeUserName()后仅返回结果,未赋值给显示用变量,导致页面仍渲染原始HTML内容。

修正后的代码

.ts 文件

import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  userName = 'Angular';
  sanitizedUserName = 'Angular'; // 新增变量存储清理后的内容

  constructor(private domSanitizer: DomSanitizer) {}

  onSave(): void {
    console.log('save clicked api call');
    this.sanitizedUserName = this.sanitizeUserName(); // 将清理结果赋值给显示变量
  }

  sanitizeUserName(): string {
    // 使用 SecurityContext.HTML 替代数字 1
    const sanitized = this.domSanitizer.sanitize(SecurityContext.HTML, this.userName);
    console.log('sanitized text/html', sanitized);
    return sanitized;
  }
}

.html 文件

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

  <div>
    <span>View : </span>
    <!-- 绑定清理后的变量 -->
    <div [innerHTML]="sanitizedUserName"></div>
  </div>

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

补充说明

  • Angular 中用插值语法{{ userName }}会自动转义HTML,但[innerHTML]会直接渲染HTML,因此必须手动做 sanitize 处理。
  • 如果需要实时显示清理后的内容,可通过ngModelChange事件触发处理:
<input type="text" [(ngModel)]="userName" name="username" (ngModelChange)="sanitizedUserName = sanitizeUserName()" />

内容的提问来源于stack exchange,提问作者user8348978

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 00:30:56