在Angular2组件类中将函数转换为变量

时间:2016-02-01 19:28:21

标签: typescript angular

如何将cellRenderer函数更改为可重用变量?我尝试使用构造函数,并声明一个变量,看起来很简单,但任何帮助都会受到赞赏。

import {Component} from 'angular2/core';

@Component({
    selector: 'app',
    template: '<ag-grid-ng2 class="ag-fresh" style="height: 300px"    [columnDefs]="columnDefs"   [rowData] = "rowData"></ag-grid-ng2>',
    directives: [(<any>window).ag.grid.AgGridNg2]
})
export class SampleAppComponent {

    columnDefs = [
        { headerName: "Make", field: "make" },
        { headerName: "Model", field: "model" },
        {
            headerName: "Price",
            field: "price",
            cellClass: 'rightJustify',
            cellRenderer: function (params: any) {
                return '$' + params.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); //thanks http://stackoverflow.com/users/28324/elias-zamaria
            }
        }
    ];
}

我在这里做错了什么?

export class SampleAppComponent {

constructor() {
    this.convertToMoney = function (params: any) {
        return '$' + params.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); //thanks http://stackoverflow.com/users/28324/elias-zamaria
    };


columnDefs = [
    { headerName: "Line Type", field: "line" },
    { headerName: "Expense Type", field: "expense" },
    {
        headerName: "Totals",
        field: "totals",
        cellClass: 'rightJustify',
        cellRenderer: convertToMoney()
    }
];

1 个答案:

答案 0 :(得分:1)

不完全确定你想要在这里实现什么,而不是听起来粗鲁,但也许首先检查打字稿的正确语法将有助于你实现,并了解你必须做什么。

无论如何......我会尽力帮助你,我相信你会喜欢这样的课程吗?

import {Component} from 'angular2/core';

@Component({
    selector: 'app',
    template: '<ag-grid-ng2 class="ag-fresh" style="height: 300px"    [columnDefs]="columnDefs"   [rowData] = "rowData"></ag-grid-ng2>',
    directives: [(<any>window).ag.grid.AgGridNg2]
})
export class SampleAppComponent {

    public columnDefs : any[] = [
        { headerName: "Line Type", field: "line" },
        { headerName: "Expense Type", field: "expense" },
        {
            headerName: "Totals",
            field: "totals",
            cellClass: 'rightJustify',
            cellRenderer: this.convertToMoney //reference to class' convertToMoney method
        }
    ];       

    constructor() {}

    private convertToMoney(params: any) : string {
        return '$' + params.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); //thanks http://stackoverflow.com/users/28324/elias-zamaria
    } 

}