Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Components - Dynamic Inline Styles

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:

  1. Is there any better way to render the <div>s count times without creating a dummy array?

  2. 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?

like image 602
AweSIM Avatar asked May 24 '16 15:05

AweSIM


2 Answers

<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}">
like image 149
Günter Zöchbauer Avatar answered Oct 05 '22 09:10

Günter Zöchbauer


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

like image 24
Abdulrahman Alsoghayer Avatar answered Oct 05 '22 09:10

Abdulrahman Alsoghayer