Reputation:
I would like to ask how to transfer a HTML format string from the .component.ts
file into the .component.html
file.
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>';
}
}
Both the text and its HTML format are defined. Thus I want to show the text with its own HTML-defination in the browser.
The layout.component.html
file looks like:
<h2>{{ htmlText }}</h2>
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.
Upvotes: 2
Views: 1005
Reputation: 256
Just need to use [innerHTML]
<div [innerHtml]="htmlText"></div>
That would be enough.
Upvotes: 0
Reputation: 543
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}`);
}
}
}
and in the html file use the following line of code:
<div [innerHtml]="htmlBody | keepHtml: 'html'"></div>
Upvotes: 1