Mam komponent o właściwości count
i color
. Element ma wyświetlać numer count
o numerze <div>
s z wbudowanym stylem używanym do zmiany koloru na color
.Elementy Angular2 - dynamiczne style śródliniowe
Oto co mam do tej pory:
@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;
}
}
Czyni:
<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>
Teraz mam dwa problemy z tym:
Czy istnieje lepszy sposób na renderowanie the
<div>
scount
razy bez tworzenia fałszywej tablicy?Co ważniejsze, style śródliniowe nie są ustawiane. Jeśli używam kodów typu hardcode, takich jak
style="color: red"
, to działa. Alestyle="color: {{color}}"
nie. Element jest renderowany bez żadnych stylów, jak widać powyżej.
Dla # 2, Próbowałem również za pomocą dzieciom nativeElement
„s, a także:
@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);
}
}
Ale otrzymuję wyjątek dostępu do elementów podrzędnych, gdyż nie istnieje widocznie.
W jaki sposób należy rozwiązać te problemy?
Nie ma mowy dla nas 'ngFor' bez tablicy. Możesz stworzyć własną dyrektywę 'ngFor' która to robi. Istnieje problem z obsługą 'ngFor' z liczbą zamiast z tablicą, ale jest mało prawdopodobne, aby została zaimplementowana. –
dziękuję za końcówkę mate .. to jednak jest do bani .. powoduje niezdarną implementację komponentów w takich przypadkach .. – AweSIM
Twój kod może być trochę zoptymalizowany. Zobacz http://stackoverflow.com/questions/36535629/repeat-html-element-multiple-times-using-ng--------o-umber-on- –