Angular2 Components - Dynamic Inline Styles

I have a component that has the count and color property. The component should display count number <div> with the built-in style used to change its color to color .

Here is what I still have:

 @Component({ selector: 'my-control', template: `<div *ngFor="let i of dummyArray" style="color: {{color}}"> COLOR = {{color}}</div>` }) export class MyControl { private _count: number; @Input() set count(value: string) { this._count = +value; } @Input() set color(value: string) { this._color = value; } get dummyArray(): number[] { let ret: number = []; for (let i = 0; i < this._count; ++i) ret.push(i); return ret; } get color(): string { return this._color; } } 

It means:

 <my-control count="5" color="red"> <div>COLOR = red</div> <div>COLOR = red</div> <div>COLOR = red</div> <div>COLOR = red</div> <div>COLOR = red</div> </my-control> 

Now I have two problems:

  • Is there a better way to render the time of a <div> count without creating a dummy array?

  • More importantly, inline styles are not set. If I am rigidly styled, for example style="color: red" , it works. But style="color: {{color}}" not. The item is displayed without any styles, as you can see above.

For # 2, I also tried using nativeElement tags:

 @Input() set count(value: string) { this._count = +value; this.update(); } @Input() set color(value: string) { this._color = value; this.update(); } update(): void { for (let i = 0; i < this._count; ++i) { this.renderer.setElementStyle(this.elRef.nativeElement.children[i], 'color', this._color); } } 

But I get an exception when referring to child elements, as they apparently don't exist.

How can I solve these problems?

+6
source share
2 answers
 <div *ngFor="let i of dummyArray" style="color: {{color}}> 

missing closure " after color}}

Binding this style to the style should be avoided, as it does not work in all versions of Safari (and possibly others).

Use instead

 <div *ngFor="let i of dummyArray" [ngStyle]="{'color': color}"> 
+15
source

About the first question:

To create an array with ten undefined elements, you can do:

 @Component({ selector: 'my-app', template: `<div *ngFor="let i of arr(10); let index=index">hello {{index}}</div>` }) export class AppComponent { arr=Array; } 

check this panel

+3
source

All Articles