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

How to use TAG style component variables in Angular 2?

I have an Angular 2 component for my header, which I like to color depending on user settings. So, I would like to assign a background color and a font. Although I know how to do this with binding an attribute to an element, I could not figure out how to use it in a style tag.

Using attribute bindings for a style works well, however, it becomes rather unpleasant for several subelements, especially if they are nested in other subcomponents. The [ngStyle] = attribute also works with only one 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> 

So, I would like to add something like

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

into the html template. However, this does not work.

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

+6
source share
3 answers

It seems to me that you are just creating a new component called "subcomponent", why not do it?

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> 
0
source

In 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}}; }` `] }) 
-2
source

Use NgStyle as described in this answer

fooobar.com/questions/1012668 / ...

shorter

 <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()}; } 
-2
source

Source: https://habr.com/ru/post/1012666/


All Articles