【问题标题】:Class bindings in Angular not working properlyAngular 中的类绑定无法正常工作
【发布时间】:2020-07-17 22:21:43
【问题描述】:

我正在尝试根据特定条件将两个类分配给一个表行,但错误的类被分配给了错误的 tr。

我的 list.component.html:

div class="country_box" *ngIf="cases">
  <div class="container">
    <input
      type="text"
      class="form-control-sm"
      name="search"
      [(ngModel)]="search"
      autocomplete="off"
      placeholder="Search by Country Name"
    />
  </div>
  <table>
    <tr>
      <th>
        <h3><strong>Country Name: </strong></h3>
      </th>
      <th>
        <h3><strong>Cases: </strong></h3>
      </th>
      <th>
        <h3><strong>Deaths: </strong></h3>
      </th>
      <th>
        <h3><strong>Recovered: </strong></h3>
      </th>
    </tr>
    <tr
      *ngFor="let country of cases[1].countries_stat | filter: search"
      [ngClass]="setClass(country)"
    >
      <td>{{ country.country_name }}</td>
      <td>{{ country.cases }}</td>
      <td>{{ country.deaths }}</td>
      <td>{{ country.total_recovered }}</td>
    </tr>
  </table>
</div>

我的 list.component.ts:

setClass(stats) {
//console.log(stats.deaths);
let myClass = {
  negative: stats.deaths > stats.total_recovered,
  positive: stats.deaths < stats.total_recovered,
};
return myClass;

}

最后是我的 list.component.css:

    .positive {
  background-color: red;
  color: #fafafa;
}

.negative {
  background-color: green;
  color: #fafafa;
}

如果有任何帮助,我将不胜感激,谢谢!

【问题讨论】:

    标签: angular class binding command-line-interface


    【解决方案1】:

    你 setClass 返回的是对象而不是类名。

    您可以尝试返回如下所示的类名吗?

    setClass(stats) {
        return stats.deaths > stats.total_recovered ? 'negative' : 'positive' ;
    }
    

    【讨论】:

    • 不幸的是,结果是一样的 :(。许多具有正恢复率的国家仍然被分配到负类。
    • 然后你可以在 tr 文件中添加 country.total_recovered ? 'negative ': '正面'">
    • 试过了,恐怕效果一样。你可以明白为什么这个问题让我头疼。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签