简体   繁体   English

将样式动态注入 Angular 组件

[英]Dynamically inject styles into Angular component

I have a component that I would like to apply CSS styles to using an object of selectors to CSS props.我有一个组件,我想将 CSS 样式应用于将选择器对象用于 CSS 道具。 https://codesandbox.io/s/happy-goldberg-4740z https://codesandbox.io/s/happy-goldberg-4740z

Styles to be applied from parent要从父级应用的样式

const styles = {
  a: [
    ['color', 'red']
  ],
  b: [
    ['color', 'blue']
  ]
};

Component to be styled dynamically要动态设置样式的组件

@Component({
  selector: 'test',
  template: `
    <div>
      <span class="a">I am A</span>
      <span class="b">I am B</span>
    </div>
  `
})
export class Test implements OnInit {
  @Input() stylesToApply: { [key: string]: string[][] };

  constructor(private _renderer: Renderer2, private _element: ElementRef) {}

  ngOnInit() {
    let styleText = '';
    Object.entries(this.stylesToApply).forEach(([key, value]) => {
        const selector = `:host ${ key }`;
        let propStr = '';
        for (let i = 0; i < value.length; i++) {
            propStr += `${ value[i][0] }: ${ value[i][1] };\n`;
        }

        styleText += `${ selector} { ${ propStr } }\n`;
    });

    const styleElement = this._renderer.createElement('style');
    this._renderer.appendChild(styleElement, this._renderer.createText(styleText));
    this._renderer.appendChild(this._elementRef.nativeElement, styleElement);
  }
}

The result should be a <style> element injected into Test like so but the styles are not actually applied to the elements:结果应该是一个<style>元素注入到Test ,但样式实际上并未应用于元素:

<style>
:host a { color: red; }
:host b { color: blue; }
</style>

The angular docs have a good starting guide on how to achieve this here angular 文档有一个很好的入门指南,说明如何在此处实现这一目标

You need have an object that contains property CSSStyleDeclaration.您需要一个包含属性 CSSStyleDeclaration 的对象。 ie IE

myStyle: CSSStyleDeclaration = { width: '100px', minHeight: '200px', backgroundColor: 'red' }

then in your component you could do something along the lines of然后在你的组件中你可以做一些类似的事情

<div [style]="myStyle"></div>

this allows you to pass the style directly into the element.这允许您将样式直接传递到元素中。

another option at your disposal is to use @HostBinding , but that's probably less ideal for what you are trying to do您可以使用的另一种选择是使用@HostBinding ,但这对于您想要做的事情来说可能不太理想

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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