Render CSS для innerHtml с помощью angular2
Я пытаюсь отобразить HTML-шаблон с помощью innerHTML и строки html + css, которые я получаю из SQL.
Пример строки шаблона:
<html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Template Name</title><style type="text/css"> p{ color:red; }</style> </head> <body> <h1>#headding#</h1> <p style="color:red;">#paragraph#</p><a href="#url#">#urltext#</a> </body> </html>
Теперь он отлично отображает HTML, но похоже, что он удаляет теги стиля и просто отображает текст внутри него.
Пример рендера:
![введите описание изображения здесь]()
Часть рендеринга HTML:
<div [innerHtml]="templateBody">
</div>
Части сайта Home.component.ts:
@Component({
selector: "home",
templateUrl: `client/modules/home/home.component.html`,
encapsulation: ViewEncapsulation.Emulated
})
export class HomeComponent implements OnInit{
templateBody: string;
.....other code
}
Я пробовал его с инкапсулированием: ViewEncapsulation.Emulated/None и т.д., попробовал встроенный CSS, и я попытался добавить: host → > infront из тега p. Все они делают то же самое.
Любые предложения?
Ответы
Ответ 1
Используйте его с DomSanitizer с помощью bypassSecurityTrustHtml и SafeHtml, как показано ниже,
DEMO: https://plnkr.co/edit/eBlzrIyAl0Il1snu6WJB?p=preview
import { DomSanitizer } from '@angular/platform-browser'
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
console.log(this.sanitized.bypassSecurityTrustHtml(value))
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
@Component({
selector: 'my-app',
template: `
<div [innerHtml]="html | safeHtml"></div>
`,
})
export class App {
name:string;
html: safeHtml;
constructor() {
this.name = 'Angular2'
this.html = `<html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Template Name</title><style type="text/css"> p{ color:red; }</style> </head> <body> <h1>#headding#</h1> <p style="color:red;">#paragraph#</p><a href="#url#">#urltext#</a> </body> </html>`;
}
}
Ответ 2
Внесите Sanitizer
и примените bypassSecurityTrustHtml(value: string) : SafeHtml
к содержимому HTML, как показано в https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html, чтобы сообщить Angular2, что вы доверяете содержимому.
См. также В RC.1 некоторые стили нельзя добавить с помощью синтаксиса привязки
Ответ 3
Я сделал это без каких-либо трубок и просто ввел DomSanitizer и SafeHtml в свой компонент и выполнил команду bypassSecurityTrustHtml в моей строке разметки. Это позволило мне сохранить мои встроенные стили от разбора.
import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: "foo",
templateUrl: "./foo.component.html"
})
export class FooComponent {
html: SafeHtml;
constructor(private sanitizer: DomSanitizer) {
this.html = this.sanitizer.bypassSecurityTrustHtml('<span style="color:##0077dd">this works</span>');
}
}
и в шаблоне foo.component.html
<div [innerHtml]="html"></div>