Angular 2 - 如何从ts文件传递管道

时间:2017-03-15 06:12:19

标签: angular

app.component.ts

    export class AppComponent {

    private productdata = [{
        "ProductName": "Chang",
        "UnitPrice": 18.0000,
    },
    {
        "ProductName": "Chai",
        "UnitPrice": 22.0000,
    }
    ]; 
   }

app.component.html

<table class="table">
    <tr>
        <th>Product Name</th>
        <th>Price</th>
    </tr>
    <tr *ngFor="let data of productdata">
        <td>
            {{data.ProductName}}
        </td>
        <td>
            {{data.UnitPrice | currency:'USD':true:'1.2-2'}}
        </td>
    </tr>
</table> 

上面的代码工作正常。现在,我试图从ts文件传递货币管道,如:

ts文件中的

public format: any = currency:'USD':true:'1.2-2';

在html文件中

<td>
        {{data.UnitPrice | format}}
</td>

但它不起作用。这是一种正确的方式来应用这样的货币过滤器吗?有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

管道实际上不是字符串值。所以你可以这样做:

public format: string = 'USD';
HTML中的

<td>
     {{data.UnitPrice | currency:format}}
</td>

使其更具活力

public pipe: any = {
    name: 'currency',
    format: 'USD'
}
HTML中的

<div *ngIf="pipe.name=='currency'">
    <div>{{value|currency:pipe.format}}</div>
</div>
<div *ngIf="pipe.name=='date'">
    <div>{{value|date:pipe.format}}</div>
</div>

或使用开关

<div [ngSwitch]="pipe.name">
    <div *ngSwitchCase="'currency'">
        <div>{{value|currency:pipe.format}}</div>
    </div>
    <div *ngSwitchCase="'date'">
        <div>{{value|date:pipe.format}}</div>
    </div>
</div>