Angular 在视图模板中创建样式标签? [英] Angular Create Style Tag in View Template?
问题描述
我想创建一个通用的 html 片段组件.我们的想法是我们可以将 html 片段存储在某个 db 中,以及应该应用于它们的样式.
我可以轻松地设置 innerHtml 以将 html 结构插入到我的视图模板中的基本元素中,但是如何在我的视图模板中动态插入 <style>
标签?
这是我所拥有的:
@Component({模块 ID:module.id,选择器:'htmlFragment',styleUrls: ['html-fragment.css'],templateUrl:'html-fragment.html'})导出类 HtmlFragmentComponent {@Input() htmlContent: 字符串;@Input() styleContent: 字符串;}
这是视图模板:
<style [innerHTML]="styleContent"></style><div [innerHTML]="htmlContent"></div>
然后我尝试像这样使用它:
<htmlFragment [htmlContent]='dHtml' [styleContent]="sHtml"></htmlFragment>
地点:
dHtml: string = 'hello this is html- bla bla
- bla bla 2
';sHtml: string = 'ul{list-style-type: none;}';
html 片段正确注入这里:
<div [innerHTML]="htmlContent"></div>
但是这里的样式元素:
<style [innerHTML]="styleContent"></style>
工作不正常.有没有办法做到这一点?
不能在模板本身中完成(Angular 模板编译器不允许这样做,只会删除任何标签),但它可以在组件内以编程方式完成:
ngOnInit() {const css = 'a {颜色:粉红色;}';const head = document.getElementsByTagName('head')[0];const style = document.createElement('style');style.type = 'text/css';style.appendChild(document.createTextNode(css));head.appendChild(style);}
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);
}
这篇关于Angular 在视图模板中创建样式标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!