【问题标题】:if then elseif then else then - statement in Angular 4if then elseif then else then - Angular 4 中的语句
【发布时间】:2018-08-02 05:56:35
【问题描述】:

我必须根据我的 angular 4 项目中的 status 条件,将我的 4 个可用类(黄色、绿色、红色和白色)中的一个类应用到我的 div

<div *ngIf="item.status=='pending'; then yellow 
elseif item.status=='completed'; then green ... else white">
div content...
</div>

上述语句中只有一个条件为真。

如何实现这一点(if elseif elseif ... else angular4 中的语句)?

【问题讨论】:

  • 使用三元运算符或对象。
  • 使用ngClass .. 有很多重载
  • 你能在回答部分解释更多吗

标签: angular ionic2 ionic3 angular2-directives


【解决方案1】:

使用ngClass

<div [ngClass]= { 
    'yellow-class' : item.status =='pending', 
    'green-class' : item.status == 'completed', 
    'white-class' : item.status != 'pending' && 'item.status' != 'completed' }>
</div>

使用ngStyle

在标记中:

<div [style.color]=“getStatusColor(item.status)”>
</div>

<div [ngStyle]=“{color: getStatusColor(item.status)”>
</div>

在组件中:

getStatusColor(status) {
  switch (status) {
    case ‘pending’:
      return ‘yellow’;
    case ‘completed’:
      return green;
    default:
      return ‘white’;
  }
}

【讨论】:

    【解决方案2】:

    您还可以从后端逻辑中获取类名,如下所示:

    <div [ngClass]="GetClassName(item.status)">
        //div content...
    </div>
    
    GetClassName(status:string):string{
        let className:string='white';
        if(status=='pending')
        {
            className='green';
        }
        else if(status=='complete')
        {
            className='yellow';
        }
        .......
    
    
        return className;
    }
    

    【讨论】:

      【解决方案3】:

      如果这些是类,那么您不需要 *ngIf 而是需要 ngClass

      像这样使用它

      <div 
        ngClass="{yellow: item.status=='pending',
                  green: item.status=='completed',
                  white: item.status!='pending' && item.status!='completed'
                 }"
      >
      ...
      </div>
      

      【讨论】:

      • 它不工作。在检查时我得到了这个:
        ...