要将静态HTML文件注入到Angular 7+组件视图中,可以使用Angular的内置DomSanitizer
服务和innerHTML
属性。以下是一个解决方法的代码示例:
html-injection.component.ts
的组件文件,并添加以下代码:import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-html-injection',
template: `
`,
styleUrls: ['./html-injection.component.css']
})
export class HtmlInjectionComponent implements OnInit {
@ViewChild('container', { static: true }) container: ElementRef;
htmlContent: SafeHtml;
constructor(private sanitizer: DomSanitizer) { }
ngOnInit() {
// 获取静态HTML文件的内容
const html = `
Hello, World!
This is a static HTML content injected into Angular component view.
`;
// 使用DomSanitizer服务将HTML内容转换为安全HTML
this.htmlContent = this.sanitizer.bypassSecurityTrustHtml(html);
}
}
html-injection.component.css
的样式文件,并添加样式(可选)::host {
display: block;
padding: 20px;
background-color: #f5f5f5;
}
app.module.ts
中:import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HtmlInjectionComponent } from './html-injection.component';
@NgModule({
declarations: [
AppComponent,
HtmlInjectionComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
中:
现在运行应用程序,你将看到静态HTML内容被注入到HtmlInjectionComponent
组件的视图中。