Angular: How to conditionally apply a style by using Date Pipe in the condition?

99封情书 提交于 2021-02-11 18:11:49

问题


I have an array in my component.ts and I want to loop in it in my component.html then inside that array contain a date, so with data I want to run a condition, if that date is greater than the current date then apply a specific style, if not then apply another style. For example something like this:

<div class="container">
  <div *ngFor="let t of table; let i = index">
    <div [ngStyle]="{'background-color': t.date > | t:today ? 'red' : 'green'}">
      <ul class="otherStyle">
        <li>{{t.name}}</li>
        <span>{{t.date}}</span>
      </ul>
    </div>
  </div>
</div>

回答1:


Let's say you have an array of dates:

export class AppComponent  {
  dates = ['2018-12-19', '2018-12-20', '2018-12-22'];
  todayDate = new Date();
}  

And your template:

<div class="container">
   <div *ngFor="let d of dates; let i = index">
        <div [ngStyle]="{'background-color':  (d | date:today) > (todayDate | date:today) ? 'green' : 'red'}">
            <ul class="otherStyle">
                <li>{{d |date:today}}</li>
            </ul>
        </div>
    </div> 
</div>

Here is an example: Stackblitz



来源:https://stackoverflow.com/questions/53890229/angular-how-to-conditionally-apply-a-style-by-using-date-pipe-in-the-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!