In angular how to implement *ngIf with If .. then.. else condition inside a <td> tag?

a 夏天 提交于 2019-12-24 11:35:50

问题


I have tried to show the if else condition inside block of table using ngIf but i am not able to display it.

  <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>

回答1:


else and then can only used on ng-templates if you want conditional styles you could use ngClass or just add a single class using [class.someClass] ="condition" or manipulate the style using [style.'some property'] since you're using ngStyle try this in your component.ts you can have a function that returns your style depending on conditions such as your !client.auditorGroup

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

and then in your 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>



回答2:


You need to provide a reference to a template:

<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>

If you want to toggle the style based on the condition, you can use a method:

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

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

  return { color: 'green' }
}



回答3:


you can use [ngClass] & conditionally assign to keep it simple.

NgClass logically groups css prop's together which is neat.

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


来源:https://stackoverflow.com/questions/53166564/in-angular-how-to-implement-ngif-with-if-then-else-condition-inside-a-td

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