Angular中如何将HTML格式字符串从component.ts传递到component.html
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 = '<b>title</b>...'; // 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

