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

Angular中如何将HTML格式字符串从component.ts传递到component.html

How to Render HTML String from .component.ts to .component.html in Angular

Got it, let's walk through how to get your HTML-formatted string from the TypeScript file to the template and actually render it as HTML instead of plain text.

The Core Issue

Right now, if you just use {{ htmlText }} in your template, Angular will treat your escaped HTML string (<b>title</b>...) as plain text. To make Angular parse and render it as actual HTML, you need to use the [innerHTML] property binding.

Step 1: Keep Your TypeScript Code (or Adjust as Needed)

Your existing LayoutComponent setup is fine—whether your HTML string is escaped (like your example) or raw HTML, the approach works. Here's your code for reference:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.css']
})
export class LayoutComponent implements OnInit {
  htmlText: string;

  constructor() { }

  ngOnInit() {
    this.htmlText = '<b>title</b>...';
    // You could also use raw HTML directly: this.htmlText = '<b>title</b>...';
  }
}

Step 2: Update Your Template to Use [innerHTML]

Open layout.component.html and replace any plain interpolation with the [innerHTML] binding. This tells Angular to process the string as HTML:

<!-- ❌ Don't do this (shows plain text): {{ htmlText }} -->
<!-- ✅ Do this to render HTML: -->
<div [innerHTML]="htmlText"></div>

Handling Unsafe HTML (If Needed)

Angular automatically sanitizes content passed to [innerHTML] to protect against XSS attacks. If your HTML includes potentially unsafe content (like scripts, iframes, or custom attributes) that you trust completely, you'll need to use DomSanitizer to mark it as safe.

Here's how to adjust your component:

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

@Component({
  selector: 'app-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.css']
})
export class LayoutComponent implements OnInit {
  safeHtmlText: SafeHtml;

  constructor(private sanitizer: DomSanitizer) { }

  ngOnInit() {
    const rawHtml = '&lt;b&gt;title&lt;/b&gt;...';
    // Mark the HTML as safe to bypass sanitization
    this.safeHtmlText = this.sanitizer.bypassSecurityTrustHtml(rawHtml);
  }
}

Then update your template to use the sanitized value:

<div [innerHTML]="safeHtmlText"></div>

⚠️ Important Note: Only use bypassSecurityTrustHtml if you fully trust the source of the HTML string. Using it with untrusted content (like user input) can expose your app to cross-site scripting (XSS) vulnerabilities.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:29:03