1

I have build a component and I want to make it more reusable, so I can use it in more projects. I want to pass a stylesheet reference when I create the component on a template, something like this:

<dynamic-css [myStyle]= "route/my-stylesheet.css"></dynamic-css>

My first aproach is to link it inside the component template, something like this:

<link rel="stylesheet" [attr.href]="myStyle">
<div>My dynamic-css component content</div>

But I don't work, the console throws an error;

can't find property 'css' of undefined

Here is a dummy version of my component:

@Component({
    selector:'dynamic-css',
    template: `
         <link rel="stylesheet" [attr.href]="myStyle">
         <div>My dynamic-css component content</div>
    `
})

export class DynamicCssComponent{
    @Input myStyle:string;
}

Is there any aproach to pass a href correctly to the component, or other way to set a stylesheet dynamicaly?

Miguel
  • 709
  • 7
  • 21

1 Answers1

1

Well, you need to surround your bind in quotes '' because the templating engine is looking for the property css on a variable by the name of route/my-stylesheet.css:

<dynamic-css [myStyle]="'route/my-stylesheet.css'"></dynamic-css>

Then you'll need to deal with attacks by implementing a pipe to ignore the sanitization per Correct way Provide DomSanitizer to Component with Angular 2 RC6

import { Pipe } from "@angular/core"; import { DomSanitizer } from "@angular/platform-browser";

@Pipe({ name: 'safe' }) export class SafePipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform(url) { return this.sanitizer.bypassSecurityTrustResourceUrl(url); } }

Finally, declare the pipe in the module and apply the pipe on your component:

module

import { SafePipe } from "./safe.pipe";
@NgModule({
  <...>
  declarations: [ App, DynamicCssComponent, SafePipe ], <...> }

component we will bind directly to href with the applied pipe

<link rel="stylesheet" [href]="myStyle | safe">

Here's a plunker with a working demo: http://plnkr.co/edit/UOkl9jqulXklf48iJiuz?p=preview

Community
  • 1
  • 1
silentsod
  • 8,165
  • 42
  • 40
  • I've worrked arround with the DomSanitize previously, but seems that my real problem was that single quotes in the property binding: [myStyle]="'route/my-stylesheet.css'". Thanks! – Miguel Nov 14 '16 at 17:10