Angular Create Style Tag in View Template?
By default, Angular will gobble <style>
elements and put them into the default Angular CSS pipeline. You can bypass this by:
@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>
`);
}
}
It has drawbacks, like requiring the wrapping div container. You also must ensure you don't allow user submitted content in this tag because it opens you up to XSS attacks. If you must, then you need to ensure the content is safe before passing it into bypassSecurityTrustHtml.
It cannot be done in the template itself (Angular template compiler does not allow it, and will just remove any <style>
tag), but it can be done programmatically within the component:
ngOnInit() {
const css = 'a {color: pink;}';
const head = document.getElementsByTagName('head')[0];
const style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
head.appendChild(style);
}