在视图模板中按角度创建样式标签? [英] Angular Create Style Tag in View Template?

查看:62
本文介绍了在视图模板中按角度创建样式标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个通用的html片段组件.我们的想法是我们可以将html片段存储在db中的某个位置,以及应应用于它们的样式.

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.

我可以轻松地将innerHtml设置为将html结构插入视图模板的基本元素中,但是如何在视图模板中动态插入<style>标签?

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?

这就是我所拥有的:

 @Component({
    moduleId: module.id,
    selector: 'htmlFragment',
    styleUrls: ['html-fragment.css'],
    templateUrl:'html-fragment.html'
})

export class HtmlFragmentComponent {

    @Input() htmlContent: string;
    @Input() styleContent: string;
}

这是视图模板:

<style [innerHTML]="styleContent"></style>
<div [innerHTML]="htmlContent"></div>

然后我要像这样使用它:

Then I'm trying to use it like this:

 <htmlFragment [htmlContent]='dHtml' [styleContent]="sHtml"></htmlFragment>

位置:

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;}';

在此处正确插入了html片段:

The html fragment is properly injected in here:

<div [innerHTML]="htmlContent"></div>

但是这里的样式元素:

 <style [innerHTML]="styleContent"></style>

工作不正常.有办法吗?

isn't working right. Is there a way to do this?

推荐答案

它不能在模板本身中完成(Angular模板编译器不允许这样做,只会删除任何<style>标记),但是可以做到在组件中以编程方式:

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);
}

这篇关于在视图模板中按角度创建样式标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆