簡體   English   中英

你如何產生動態<style> tag content in Angular template at runtime?

[英]How do you generate dynamic <style> tag content in Angular template at runtime?

我有一個在運行時動態生成mat-checkbox的 Angular 組件,我需要用不同的顏色以不同的方式更改每個復選框的單個背景,而且我沒有(不會)事先獲得信息,僅在運行時可用。

我有以下復選框的ng-template

<ng-template #renderCheckbox let-id="id" let-attr="attr">
  <mat-checkbox 
    [checked]="attr.show"
    [color]="'custom-' + id"
    (change)="onChange($event.checked, attr)">
    {{attr.name}}
  </mat-checkbox>
</ng-template>

其中,模板中的attr具有以下接口類型,這些信息來自Highcharts系列,我不想對color進行硬編碼。

interface LinkedSeriesAttributes {
  id: string;
  name: string;
  index: number;
  color: string;
  checked: boolean;
}

由於無法事先創建 css 類,也無法直接將顏色應用於mat-checkbox ,因此我只能在模板的開頭生成<style>...</style>

在我的組件中,我有代碼可以生成樣式,它會給我這樣的東西:

  .mat-checkbox.mat-custom-hello.mat-checkbox-checked .mat-checkbox-background::before {
    color: #6E8BC3 !important;
  }

  .mat-checkbox.mat-custom-world.mat-checkbox-checked .mat-checkbox-background::before {
    color: #9ED6F2 !important;
  }
  ...

但是,我嘗試了各種方法將其轉儲到<style>但沒有成功。 我試過:

<style>{{ dynamicCSSStyles }}</style>

其中,我的 IDE 顯示這是花括號的錯誤,盡管它編譯得很好並且沒有錯誤地運行,但我什么也沒得到,甚至看不到<style>標記。

我還嘗試將<style>包含在我的dynamicCSSStyles變量中,而 angular 只是將整個內容轉儲為文本...

在 Angular 中生成<style>的正確方法是什么?

我發現的“使這項工作”真正骯臟的方式,但它會導致角,以保持加入<style>回DOM。

首先,將encapsulation設置為ViewEncapsulation.None

其次,創建一個函數來生成帶有 id的舊時尚方式的<style>標簽:

  updateDynsmicStyleNode() {
    const id = 'dynamic-css-styles';
    const nativeElm = this.elmRef.nativeElement;
    const existing = nativeElm.querySelector(`style#${id}`);
    if (!existing) {
      const styleTag = document.createElement('style');
      styleTag.setAttribute('id', id);
      styleTag.innerHTML = this.dynamicCSSStyles;
      nativeElm.prepend(styleTag);
    } else {
      existing.innerHTML = this.dynamicCSSStyles;
    }
  }

第三,在ngAfterViewChecked調用我們的函數:

  ngAfterViewChecked() {
    this.updateDynsmicStyleNode();
  }

我的意思是雖然這有效,但它真的很糟糕,因為在屏幕上移動鼠標會導致 Angular 不斷地重新插入<style>標簽。

有沒有人知道其他更合法的存檔方式? 哈哈

您可以使用ngClass[class]屬性。 因為您可以從 component.ts 文件准備好樣式。

你可以這樣做:

Way 1: If you already know what the dynamic ids might be, (like if it always will be 'hello' and 'world')

let dynamicClasses = {};

// Once you get some classes from your logic, you can add them to the object above

dynamicClasses['hello'] = 'custom-hello';
dynamicClasses['world'] = 'custom-world';

// Then in HTML
<mat-checkbox [ngClass]="dynamicClasses"></mat-checkbox>



Way 2: If you dont know what the classes also might be, like if its not always be hello or world, then create a method and call it where required, you might need to do something similar to @codenamezero said. 

暫無
暫無

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

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