简体   繁体   中英

How to dynamically add styles to Angular 2 component

How could I add something like this:

<style>
    {{customStyles()}}
</style>

Style tag is being cut off from template. It's initially unknown, which style will be applied to which element.

In Angular tutorial there is explained how to add styles to template, if template was defined as string in @Component decorator, but I found no information what to do if template is HTML file.

In Angular Create Style Tag in View Template? there is given a hack, not a framework tool, thus it does not answer the question.

You can bypass Angular restriction by using a DomSanitizer :

@Component({
  template: `<div [innerHTML]="styles"></div>`
})
export class OutputStyleTagComponent implements OnInit {
  public styles: SafeHtml;

  constructor(
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit() {
    this.styles = this.sanitizer.bypassSecurityTrustHtml(`
      <style>
       .my-styles {
         ...
       }
      </style>
    `);
  }
}

This answer is an extract of this other question/answer , i've added it here because it took me some minutes to find it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM