22

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.component.ts

customCss : any;

constructor(){}

ngOnInit(){
   this.customCss['color'] = "red";
}

app.component.html

<div>
   <span class="custom_css">This is angular 5 application</span>
</div>

<style>
   .custom_css{
      color: {{customCss.color}};
   }
</style>

When I inspect the custom_css class in browser then in style it shows

.custom_css{
   color: {{customCss.color}};
}

Any help is appreciated.

3
  • Have a look at this stackoverflow.com/a/46536494/112104 Commented Mar 23, 2018 at 12:45
  • Its working on all other cases but doesn't work for css part. Commented Mar 23, 2018 at 12:49
  • I don't this Angular will allow you to have style in template. But it's easy to create dynamic element. Commented Mar 23, 2018 at 12:52

4 Answers 4

16

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;
}
Sign up to request clarification or add additional context in comments.

Comments

10

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>

1 Comment

You can however use var() like this <div [style.color]="'var(--poop)'">poop</div> where you've defined :host { --poop: brown; }. You wouldn't want to typically do this but that's how you could.
9

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.