我有以下组件:
@Component({
template: `
<div class="container">
<div *ngFor="let connection of connections">
<div class="row">
<div class='col-2'>{{connection.arrivalTime}}</div>
<div class='col-1'>{{connection.delay}}</div>
<div class='col-2'>{{connection.actualArrivalTime}}</div>
<div class='col-1'>{{connection.icon}}</div>
<div class='col-1'><span [ngStyle]="{'background-color': connection.colors.bg}">{{connection.line}}</span></div>
<div class='col-3'>{{connection.direction}}</div>
<div class='col-2'>{{connection.cancelled}}</div>
</div>
</div>
</div>
styleUrls: ['../app.component.css', '../../simple-grid.css'],
})
export class ZVVComponent {
connections: PublicConnection[] = [];
displayDate: Date;
constructor(private zvvService: ZVVService) {
this.displayDate = new Date();
zvvService.getConnections(this.displayDate).subscribe(data => {
data.forEach( (connection) => {
this.connections.push(new PublicConnection(
connection.product.line,
connection.product.longName,
connection.product.direction,
connection.cancelled,
connection.product.icon,
connection.product.color,
connection.mainLocation.time,
connection.mainLocation.countdown,
connection.mainLocation.realTime.time,
connection.mainLocation.realTime.countdown,
connection.mainLocation.realTime.delay,
connection.mainLocation.realTime.isDelayed,
connection.mainLocation.realTime.hasRealTime
));
});
});
}
}
正如你所看到的,我在其中一个div中使用了ngStyle,并希望将它绑定到包含颜色的十六进制字符串的变量connection.colors.bg:
export class Color {
get fg(): string {
return this.fg;
}
get bg(): string {
return this.bg;
}
}
然而,这不起作用,文本仍为黑色,背景为白色。我究竟做错了什么?当我更改它,并在其中写入红色而不是变量时,文本显示为红色。
以下是PublicConnection代码:
从'./color'导入{Color};
export class PublicConnection {
constructor(
public line: string,
private name: string,
public direction: string,
public cancelled: boolean,
public icon: string,
public colors: Color,
public arrivalTime: string,
private countdown: string,
public actualArrivalTime: string,
private actualCountdown: string,
public delay: string,
private isDelayed: boolean,
private hasRealtimeData: boolean
) {
this.direction = this.direction.replace('ü', 'ü');
this.direction = this.direction.replace('ö', 'ö');
this.direction = this.direction.replace('ü', 'ü');
}
}
答案 0 :(得分:0)
问题不在于ngStyle
指令 - 您正确使用它。当组件首次尝试渲染时,很可能没有加载数据。
由于您的数据是异步的,我猜测在组件渲染和设置背景颜色时,它还没有从服务中获得颜色。
在模板中将connection.color.bg
更改为connection.color?.bg
,尝试使用安全导航操作符。
在此处详细了解:https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths