I have a component that has a count
and a color
property. The component is supposed to display count
number of <div>
s with an inline style used to change its color to color
.
Here's what I have so far:
@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;
}
}
This renders:
<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 issues with this:
Is there any better way to render the <div>
s count
times without creating a dummy array?
More importantly, the inline styles are not being set. If I hardcode styles like style="color: red"
, it works. But style="color: {{color}}"
does not. The element is rendered without any styles as you can see above.
For #2, I have also tried using the nativeElement
's children as well:
@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 exception accessing the child elements as they don't exist apparently.
How should I go about solving these issues?
<div *ngFor="let i of dummyArray" style="color: {{color}}>
is missing the closing "
after color}}
Binding this way to style should be avoided because it doesn't work in all Safari versions (maybe also others).
Instead use
<div *ngFor="let i of dummyArray" [ngStyle]="{'color': color}">
About your first question:
To create an array with ten undefined
elements, you could 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 plunk
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With