簡體   English   中英

將樣式動態注入 Angular 組件

[英]Dynamically inject styles into Angular component

我有一個組件,我想將 CSS 樣式應用於將選擇器對象用於 CSS 道具。 https://codesandbox.io/s/happy-goldberg-4740z

要從父級應用的樣式

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

要動態設置樣式的組件

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

結果應該是一個<style>元素注入到Test ,但樣式實際上並未應用於元素:

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

angular 文檔有一個很好的入門指南,說明如何在此處實現這一目標

您需要一個包含屬性 CSSStyleDeclaration 的對象。 IE

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

然后在你的組件中你可以做一些類似的事情

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

這允許您將樣式直接傳遞到元素中。

您可以使用的另一種選擇是使用@HostBinding ,但這對於您想要做的事情來說可能不太理想

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM