css - 使用组件函数为 HTML 对象设置样式
<table *ngIf="datoer">
<tr>
<th>Man</th>
<th>Tir</th>
<th>Ons</th>
<th>Tor</th>
<th>Fre</th>
<th>Lør</th>
<th>Søn</th>
</tr>
<tr>
<td *ngFor="let cell of ukeEn()">
{{cell.text}}
<div class="outer" *ngIf="datoerContains(cell) != null">
<div class="circle" id="circle" *ngFor="let circle of datoerContains(cell)">
// <script>
// document.getElementById("circle").style.background-color = anyFunction();
// </script>
</div>
<div class="details" *ngFor="let circle of datoerContains(cell)">
{{circle.skole}} <br>
{{circle.kommentar}} <br>
SFO: {{circle.sfodag}}
</div>
</div>
</td>
</tr>
</table>
这是用 Angular 2 的 HTML 编写的。我想做的是,通过调用我的 component.ts 文件中的一个函数来设置类 circle 的背景颜色,该函数返回一个类似 'red' 的字符串。查看注释了解我希望它如何工作。这可能吗?如果可以,怎么做?
答案#1
你可以使用样式绑定或 ngStyle 指令:
<div class="circle" id="circle" [style.background-color]="anyFunction()"
<div class="circle" id="circle" [ngStyle]="{'background-color': anyFunction()"
直接绑定到函数是不鼓励的,因为这些函数在每个变更检测周期都会被调用。通常更高效的做法是将此类函数的结果分配给一个属性,并从视图绑定到该属性。
