我从HTTP调用中获得了大量的HTML代码。我把HTML块放在一个变量,并将它插入到我的页面[innerHTML],但我不能样式插入的HTML块。有人有什么建议吗?
@Component({
selector: 'calendar',
template: '<div [innerHTML]="calendar"></div>',
providers: [HomeService],
styles: [`h3 { color: red; }`]
})
我想要样式的HTML是包含在变量“日历”中的块。
如果你想在Angular组件中动态添加HTML元素,这可能会有帮助:
// inside component class...
constructor(private hostRef: ElementRef) { }
getContentAttr(): string {
const attrs = this.hostRef.nativeElement.attributes
for (let i = 0, l = attrs.length; i < l; i++) {
if (attrs[i].name.startsWith('_nghost-c')) {
return `_ngcontent-c${attrs[i].name.substring(9)}`
}
}
}
ngAfterViewInit() {
// dynamically add HTML element
dynamicallyAddedHtmlElement.setAttribute(this.getContentAttr(), '')
}
我的猜测是,这个属性的约定不能保证在不同版本的Angular之间是稳定的,所以当升级到新版本的Angular时,这个解决方案可能会遇到问题(尽管,在这种情况下,更新这个解决方案可能是微不足道的)。
如果你想在Angular组件中动态添加HTML元素,这可能会有帮助:
// inside component class...
constructor(private hostRef: ElementRef) { }
getContentAttr(): string {
const attrs = this.hostRef.nativeElement.attributes
for (let i = 0, l = attrs.length; i < l; i++) {
if (attrs[i].name.startsWith('_nghost-c')) {
return `_ngcontent-c${attrs[i].name.substring(9)}`
}
}
}
ngAfterViewInit() {
// dynamically add HTML element
dynamicallyAddedHtmlElement.setAttribute(this.getContentAttr(), '')
}
我的猜测是,这个属性的约定不能保证在不同版本的Angular之间是稳定的,所以当升级到新版本的Angular时,这个解决方案可能会遇到问题(尽管,在这种情况下,更新这个解决方案可能是微不足道的)。
Günter Zöchbauer推荐的版本很好,但我要做一个补充。在我的例子中,我有一个没有样式的html元素,我不知道如何样式它。因此,我设计了一个管道来添加样式。
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'StyleClass'
})
export class StyleClassPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(html: any, styleSelector: any, styleValue: any): SafeHtml {
const style = ` style = "${styleSelector}: ${styleValue};"`;
const indexPosition = html.indexOf('>');
const newHtml = [html.slice(0, indexPosition), style, html.slice(indexPosition)].join('');
return this.sanitizer.bypassSecurityTrustHtml(newHtml);
}
}
然后你可以像这样给任何html元素添加样式:
<span [innerhtml]="Variable | StyleClass: 'margin': '0'"> </span>
:
Variable = '<p> Test </p>'