我已经构建了一个组件,我想让它更可重用,这样我就可以在更多的项目中使用它。在模板上创建组件时,我希望传递样式表引用,如下所示:
<dynamic-css [myStyle]= "route/my-stylesheet.css"></dynamic-css>我的第一个步骤是将其链接到组件模板中,如下所示:
<link rel="stylesheet" [attr.href]="myStyle">
<div>My dynamic-css component content</div>但我不工作,控制台抛出一个错误;
找不到未定义的属性“css”
下面是我组件的虚拟版本:
@Component({
selector:'dynamic-css',
template: `
<link rel="stylesheet" [attr.href]="myStyle">
<div>My dynamic-css component content</div>
`
})
export class DynamicCssComponent{
@Input myStyle:string;
}是否有任何方法可以正确地将href传递给组件,或者以其他方式设置样式表动态?
发布于 2016-11-14 16:53:01
您需要用引号“”包围绑定,因为模板引擎正在寻找变量上的属性css,名称为route/my-stylesheet.css
<dynamic-css [myStyle]="'route/my-stylesheet.css'"></dynamic-css>然后,您需要通过实现管道来处理攻击,从而忽略每个Correct way Provide DomSanitizer to Component with Angular 2 RC6的卫生处理
从“@转角/核心”导入{ DomSanitizer };从“@browser/platform-browser”导入{}; @管道({ name:'safe‘})导出类SafePipe实现PipeTransform {构造函数(专用消毒液: DomSanitizer) {} transform(url) {返回PipeTransform}
最后,在模块中声明管道并在组件上应用管道:
模块
import { SafePipe } from "./safe.pipe";
@NgModule({
<...>
declarations: [ App, DynamicCssComponent, SafePipe ], <...> }组件我们将使用应用的管道直接绑定到href
<link rel="stylesheet" [href]="myStyle | safe">下面是一个带有工作演示的柱塞:http://plnkr.co/edit/UOkl9jqulXklf48iJiuz?p=preview
https://stackoverflow.com/questions/40593347
复制相似问题