[英]Styled HTML content dynamically switched with tabs using Angular 2
我试图创建一个可重用的angular2组件,该组件接受服务器上html文件的URL数组,并创建一个带有选项卡的内容窗口,以在“章节”之间切换,从而有效地替换了内容窗口中的html和css。 我已经尝试了各种方法,包括iframe,但是这些方法都行不通,我可以在StackOverflow上找到有角度的1 ng-include解决方法,但自那以后它们都已弃用,而我所拥有的最接近的方法是构建组件您可以@Input html并对其进行插值,但是样式将不适用,并且将所有样式或脚本标签剔除掉。 这是我尝试过的。
在我的父组件类中:
htmlInput: string = "<h1>Why Does Angular make this so hard?</h1>";
cssInput: string = "h1 { color:red; }"
父组件HTML:
<app-html [html]='htmlInput' [css]='cssInput'></app-html>
我的HTML组件:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-html',
template: '<div [innerHtml]=html></div>', //This works but no style
//template: '{{html}}', //This displays the actual markup on page
styles: ['{{css}}'] //This does nothing
//styles: ['h1 { color: red; }']//Also nothing
})
export class HtmlComponent implements OnInit {
@Input() html: string = "";
@Input() css: string = "";
ngOnInit() {
}
}
该代码的结果是
但是没有红色。 也许在将innerHtml添加到DOM之前应用了样式? 我不知道,但仅放置{{html}}即可显示带有可见的h1标签的实际标记。
之所以要这样做,是因为在我将所有站点共享一个样式表之前,我已经在服务器上的文件夹中创建了一堆HTML页面。 我希望能够像翻阅书本中的页面一样翻阅它们,并且由于页面太多,而且我很可能会一直添加更多内容,因此我宁愿不为每个单独的页面创建路由一。 (我已经具有用于基本站点导航的路由。)
对于在最新版本的Angular 2中如何将样式化的HTML动态地嵌入到页面中,是否有人有更好的建议? 在撰写本文时,我们处于2.0.0-beta.17中。
或...我已经认为我可能会从完全错误的角度来解决这个问题。 一定有一个原因使Angular变得如此困难并且不赞成人们提出的所有解决方案,因此如果有人对我如何以更友好的角度实现相同的结果提出了建议,我也很想听听。
谢谢。
我可以通过创建将HTML添加到iframe中的html格式消除污染的管道来解决我的问题。
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(url: string) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
然后,您只需将html传递到iframe中即可。
<iframe width="100%" height="1000" frameBorder="0" [src]="url | safe"></iframe>
这对我很有用,因为我有一些使用各种jquery和样式等的旧页面。这是显示它们的快速解决方案。
Angular2通过将动态添加的属性(例如_ngcontent-yle-18
到CSS选择器中来重写添加到组件的样式。
Angular2使用它来模拟影子DOM样式封装。 这些属性不会添加到动态添加的HTML中(例如,使用innerHTML
)。
解决方法
将样式添加到index.html
因为Angular2不会重写这些样式
设置ViewEncapsulation.None
因为这样Angular不会添加封装仿真属性
使用/deep
/使Angular2忽略封装仿真属性
您应该将css包装到一个对象中,并使用ngStyle将其绑定到组件而不是styles
属性,因为styles
不支持数据绑定。
例:
htmlInput: string = "<h1>Why Does Angular make this so hard?</h1>";
cssInput: string = "{h1 { color:red; }}"
父组件HTML:
<app-html [html]='htmlInput' [css]='cssInput'></app-html>
您的HTML组件:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-html',
template: '<div [innerHtml]="html" [ngStyle]="css"></div>',
styles: []
})
export class HtmlComponent implements OnInit {
@Input() html: string = "";
@Input() css: string = "";
ngOnInit() {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.