【问题标题】:Style HTML object using component function使用组件函数样式化 HTML 对象
【发布时间】:2016-11-15 04:50:36
【问题描述】:
<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 类的background color,该函数返回一个类似'red' 的字符串。检查 cmets 我希望它如何工作。 这可能吗?如果是,怎么做?

【问题讨论】:

    标签: html css angular typescript


    【解决方案1】:

    您可以使用样式绑定或ngStyle 指令:

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

    不鼓励直接绑定到函数,因为这些函数在每个变更检测周期都会被调用。 将此类函数的结果分配给属性并从视图绑定到该属性通常更有效。

    【讨论】:

    • 太好了,谢谢! “从视图绑定到该属性”是什么意思?比如anyFunction().color?
    • 例如,您有一个@Input set color(value: String) { this.backgroundColor = anyFunction(value); },然后使用[style.background-color]="backgroundColor"。这样您就不会直接绑定到函数。
    猜你喜欢
    • 2020-07-13
    • 2020-09-26
    • 2020-09-22
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多