MariusJ MariusJ - 26 days ago 7
TypeScript Question

Style HTML object using component function

<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>


This is written in html with Angular 2.
What I want to do, is to set the
background color
of class
circle
by calling a function from my
component.ts
file which returns a string like
'red'
. Check the comments on how I want it to work.
Is this possible? If yes, how?

Answer

You can use style binding or the ngStyle directive:

<div class="circle" id="circle" [style.background-color]="anyFunction()"
<div class="circle" id="circle" [ngStyle]="{'background-color': anyFunction()"

Directly binding to functions is discouraged though, because these functions are called every change detection cycle. It's usually more efficient to assign the result of such a function to a property and bind from the view to that property.