Use variable in style tag in angular template?

前端 未结 4 1658
野性不改
野性不改 2021-02-20 01:55

I am working on angular 5 application, and I have requirement of applying dynamic css in style tag in template. I have tried some solutions but they are not working.

app

相关标签:
4条回答
  • 2021-02-20 02:15

    By the way if you set the color like this:

    <div [style.color]="color"></div>
    

    where color='var(--cssValue)' it would not work!

    However, this works correctly:

    <div [ngStyle]="{color: color}"></div>
    
    0 讨论(0)
  • 2021-02-20 02:17

    You can use [ngStyle] directive:

    <span [ngStyle]="{'color': 'red'}">
     This is angular 5 application
    </span>
    

    Or like so:

    <span [ngStyle]="applyStyles()">
     This is angular 5 application
    </span>
    

    And in component:

    applyStyles() {
        const styles = {'color' : 'red'};
        return styles;
    }
    
    0 讨论(0)
  • 2021-02-20 02:26

    You can use [style.customClass]=“methodInComponent()”...

    This will apply the class if the method in your component returns true.

    0 讨论(0)
  • 2021-02-20 02:28

    The given answer works if you have few elements to change in a given component, if you need to change the full overall look and feel of your app based on user's choice (and on the fly), the only way i found so far is to override css in the javascript like the following:

    this.stylesService.get().subscribe(({ customStyles }) => {
         const style = document.createElement('style');
         style.innerHTML = 
         `.picture {
             background-image: url(${customStyles.backgroundUrl});
         }
         h1, h2 {
             color: ${customStyles.primaryColor};
         }`;
    
         document.body.appendChild(style);
    });
    
    0 讨论(0)
提交回复
热议问题