I want to create a generic html fragment component. The idea being we may store html fragments in a db somewhere, and styles that should be applied to them.
I can easily set the innerHtml to insert the html structure into a base element in my view template, but how do i dynamically insert a <style>
tag in my view template?
Here's what I have:
@Component({
moduleId: module.id,
selector: 'htmlFragment',
styleUrls: ['html-fragment.css'],
templateUrl:'html-fragment.html'
})
export class HtmlFragmentComponent {
@Input() htmlContent: string;
@Input() styleContent: string;
}
Here is the view template:
<style [innerHTML]="styleContent"></style>
<div [innerHTML]="htmlContent"></div>
Then I'm trying to use it like this:
<htmlFragment [htmlContent]='dHtml' [styleContent]="sHtml"></htmlFragment>
Where:
dHtml: string = '<div>hello this is html<ul><li>bla bla</li><li>bla bla 2</li></ul></div>';
sHtml: string = 'ul{list-style-type: none;}';
The html fragment is properly injected in here:
<div [innerHTML]="htmlContent"></div>
However the style element here:
<style [innerHTML]="styleContent"></style>
isn't working right. Is there a way to do this?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With