在角度如何实现* ngIf与If .. then .. else条件在标签内?

时间:2018-11-06 06:08:08

标签: angular angular6

我试图使用ngIf在表块中显示if else条件,但我无法显示它。

  <tr *ngFor="let client of clients">
<!--here i need to implement it-->
   <td *ngIf="!client.auditorGroup"; then 
   [ngStyle]="titleStyles else [ngStyle]="oldStyles1">{{client.selectionId}}</td>
   <td>{{client.selectionDate}}</td>
   <td>{{client.selectedBy}}</td>
   <td>{{client.panEximNumber}}</td>
   <td>{{client.name}}</td>
   <td>{{client.address}}</td>
   <td>{{client.phoneNumber}}</td>
   <td>{{client.selectionType}}</td>
   <td *ngIf="!client.auditorGroup" [ngStyle]="titleStyles">Edit
   Delete</td>
</tr>

3 个答案:

答案 0 :(得分:3)

您需要提供模板参考:

<table>
  <tr>
    <td *ngIf="show; else tpl">A</td>
  </tr>
</table>

<button (click)="show = !show">Toggle</button>

<ng-template #tpl><td>Else template</td></ng-template>

如果要根据条件切换样式,可以使用以下方法:

<td [ngStyle]="calcStyles(client.auditorGroup)">{{client.selectionId}}</td>

calcStyles(auditorGroup) {
  if(auditorGroup) {
    return { color: 'red' }
  }

  return { color: 'green' }
}

答案 1 :(得分:2)

您可以使用[ngClass]和有条件的赋值使其保持简单。

NgClass在逻辑上将整齐的CSS道具分组在一起。

<td *ngIf="!client.auditorGroup" [ngClass]="{'class1': client.auditorGroup,  'class2': !client.auditorGroup}"></<div>

答案 2 :(得分:1)

else,然后仅在ng-templates上使用,如果您需要条件样式,则可以使用ngClass或使用[class.someClass] ="condition"添加单个类或使用[style.'some property']来处理样式,因为您使用的是ngStyle尝试这个 在component.ts中,您可以具有一个根据条件来返回样式的函数,例如!client.auditorGroup

getStyle(value) { 
if(!value)
  return this.titleStyles;
}else {
  return this.oldStyles1;
}

,然后在您的component.html

<tr *ngFor="let client of clients">
<!--here i need to implement it-->
   <td 
   [ngStyle]="getStyle(client.auditorGroup)">{{client.selectionId}}</td>
   <td>{{client.selectionDate}}</td>
   <td>{{client.selectedBy}}</td>
   <td>{{client.panEximNumber}}</td>
   <td>{{client.name}}</td>
   <td>{{client.address}}</td>
   <td>{{client.phoneNumber}}</td>
   <td>{{client.selectionType}}</td>
   <td [ngStyle]="getStyle(client.auditorGroup)">Edit
   Delete</td>
</tr>