9
votes

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:

3
#header, #header a { is a CSS selector that selects the element with the id header and it's child <a> element. I wouldn't expect template variable to work within style tags. You should rather use ngStyle. Also binding to methods in the view ="changeBackground()" is discouraged because it is called for every change detection cycle. Rather assign the result to a property and bind the view to the property instead. - Günter Zöchbauer
I know this question is a bit old now, but this answer might help you stackoverflow.com/a/48265526/1389807 - tehlivi

3 Answers

1
votes

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>
-2
votes

To your @Component object, add

styles:[ `#header, #header a {
  color: {{mycolor}};
}`]

So for example:

@Component({
  template: `<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>`,
  styles: [ `#header, #header a {
    color: {{mycolor}};
    }`
  `]
})
-3
votes

Use NgStyle as explained in this answer

https://stackoverflow.com/a/41903349

in short

<header id="header" [ngStyle]="getStyle()">
  <div>
    Some Text
    <a href="asdf">Some Link</a>
    <subcomponent></subcomponent>
  </div>
  <div> ... a lot mor stuff </div>
</header>

and

getStyle(): any {
    return {"background-color" : this.changeBackgroundColor()};
}