Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use component variable within css / style tag in Angular 2?

Tags:

css

angular

How can I use component variables within style TAG in Angular 2?

I do have an Angular 2 component for my header which I like to color depending on a users setting. Thus I'd like to assign an background and font color. While I know how to to this with an attribute binding to an element, I couldn't figure out how to use in a style tag.

Using attribute binding for style works well, however this gets pretty anoying for several subelements, especially if they are nested within other sub components. [ngStyle]= attribute is also only working on a single element.

<header id="header" [style.background-color]="changeBackground()">
  <div>
    Some Text
    <a href="asdf">Some Link</a>
    <subcomponent></subcomponent>
  </div>
  <div> ... a lot mor stuff </div>
</header>

Thus I'd like to add something like

<style>
#header, #header a {
  color: {{mycolor}};
}
</style>

to the html template. However this is not working

Similar Questions do not answer this question yet and only show attribute binding as a solution:

  • Angular2 dynamic change CSS property
  • Dynamically updating css in Angular 2
  • https://scotch.io/tutorials/all-the-ways-to-add-css-to-angular-2-components
  • https://coryrylan.com/blog/introduction-to-angular-2-ngclass-and-ngstyle
like image 895
Manuel Avatar asked Nov 25 '16 23:11

Manuel


People also ask

Can we use both CSS and SCSS in Angular?

You can have both but you have to set your style extension to SASS or CSS only.

What are the two component decorator metadata properties used to set up CSS styles for a component?

You have used both styles and styleUrls metadata properties to style your component's HTML template.


1 Answers

It looks to me like you are just creating a new component called 'subcomponent', why not do that?

subcomponent.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'subcomponent',
  templateUrl: './subcomponent.html',
})
export class SubComponent {
  mycolor = 'blue';
}

subcomponent.html:

<style>
#header, #header a {
  color: {{mycolor}};
}
</style>
like image 68
ppovoski Avatar answered Oct 21 '22 14:10

ppovoski