如何将HTML-String从component.ts传输到component.html [英] How to transfer HTML-String from component.ts to component.html
问题描述
我想问一下如何将HTML格式的字符串从 .component.ts
文件传输到 .component.html
文件中.
I would like to ask how to transfer a HTML format string from the .component.ts
file into the .component.html
file.
在我的应用程序中有一个布局文件夹. layout.component.ts
文件具有以下代码:
In my App there is a layout folder. The layout.component.ts
file has the code:
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> Title Hier <FONT color="blue"><i>some texts hier.</i></FONT>';
}
}
均定义了文本及其HTML格式.因此,我想在浏览器中显示具有自己的HTML定义的文本.
Both the text and its HTML format are defined. Thus I want to show the text with its own HTML-defination in the browser.
layout.component.html
文件如下所示:
<h2>{{ htmlText }}</h2>
编译后,浏览器显示htmlText字符串的全文,但HTML格式只是被忽略了.
After compiling the browser shows the full text of the htmlText string, but the HTML format was just ignored.
我做错了什么?感谢您提供的任何提示+帮助.
What have I done wrong? Thanks for any kind of hint+help.
推荐答案
使用以下代码创建管道:
create a pipe with the following code:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({ name: 'keepHtml', pure: false })
export class SafePipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
public transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this._sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this._sanitizer.bypassSecurityTrustStyle(value);
case 'script':
return this._sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this._sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this._sanitizer.bypassSecurityTrustResourceUrl(value);
default:
throw new Error(`Unable to bypass security for invalid type: ${type}`);
}
}
}
,并且在html文件中,使用以下代码行:
and in the html file use the following line of code:
<div [innerHtml]="htmlBody | keepHtml: 'html'"></div>
这篇关于如何将HTML-String从component.ts传输到component.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!