简体   繁体   English

在if指令中使用if指令

[英]Using if directive in for directive at angular

I'm using angular. 我正在使用角度。 I'm creating a table dynamically. 我正在动态创建一个表。 So I'm creating with ngFor directive. 所以我用ngFor指令创建。 But, type of some columns are Date. 但是,某些列的类型是日期。 So, I want casting that. 所以,我想铸造那个。 So, I want to use if case. 因此,我想使用if情况。 I wrote below like c# razor syntax. 我在下面写的像c#razor语法。 But, how can I do in angular? 但是,我该怎么做呢?

<tr [pSelectableRow]="rowData">
  <td *ngFor="let col of columns">
    if(col.type == "Date")  ???????????
       {{rowData[col.field] | date:'dd/MM/yyyy'}}
    else   ???????????????
        {{rowData[col.field] }}
  </td>
</tr>
<tr [pSelectableRow]="rowData">
  <td *ngFor="let col of columns">
    <ng-container *ngIf="(rowData[col.type] == 'Date'); else defaultTemplate;">
       <span>{{rowData[col.field] | date:'dd/MM/yyyy'}}</span>
    </ng-container>
    <ng-template #defaultTemplate>
        <span>{{rowData[col.field] }}</span>
    </ng-template>
  </td>
</tr>

Can you check this? 你能检查一下吗?

 <tr [pSelectableRow]="rowData">
      <td *ngFor="let col of columns">
        <div  *ngIf = "rowData[col.type] == "'Date'" >
           {{rowData[col.field] | date:'dd/MM/yyyy'}}
        </div>
        <div  *ngIf = "rowData[col.type] != "'Date'" >
            {{rowData[col.field] }}
      </div>
    </td>
    </tr>

Check this out 看一下这个

 data = [ {"name":"row1", "type": "date", "value": "Wed Oct 10 2018"}, {"name":"row2", "type": "email", "value": "test@test.com"}, {"name":"row3", "type": "date", "value": "Wed Oct 10 2018"}, {"name":"row4", "type": "phone", "value": "+919876543210"} ]; 
 <tr *ngFor="let row of data"> <td>{{row.name}}</td> <td>{{row.type}}</td> <td>{{row.type=='date' ? (row.value | date:'dd/MM/yyy') : (row.value)}}</td> </tr> 

I found the solution by @NIVINCEN's answer help. 我通过@NIVINCEN的答案帮助找到了解决方案。 The solution is ternary if . 如果为, 解为三元 By using ternary if, you can do with only one row code and without using any span, div or ng-template. 通过使用三元if,您只能使用一行代码,而无需使用任何span,div或ng-template。

<tr [pSelectableRow]="rowData">
  <td *ngFor="let col of columns">
    {{ col.type =='Date' ? (rowData[col.field] | date:'dd/MM/yyyy') : rowData[col.field]}}
  </td>
</tr>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM