如何在AG网格范围中获取组件变量

时间:2020-02-26 09:56:41

标签: angular ag-grid ag-grid-angular

export class HospiComponent {

    countries:CountryModel[];

    constructor(public router: Router, private masterService:MasterService, private hospitalService:HospitalService) { 
        this.loadCountry();

        this.columnDefs = [
              { headerName: 'Id', field: 'hospiId', width: 75 },
              { headerName: 'Name', field: 'compaVaNameEn', width: 250 },
              { headerName: 'cotryId', field: 'orgsmId', width: 100, valueGetter:  countryNameGetter }
        ];

        this.defaultColDef = { resizable: true };
        this.service.getHosps().subscribe(response => {
          this.rowData = response['result'];
        })

        function countryNameGetter (params) {
            console.log(params.data.orgsmId + JSON.stringify(this.organisms));
            return this.countries.filter(item => item.cotryId === params.data.cotryId).name; // this is not working as countries is not available in this scope
        }
    }

    loadCountry(){
        this.countries = [{"cotryId":25,"name":"Russia"},{"cotryId":35,"name":"Kuwait"}];
    }
}

Ag网格用于显示网格数据。国家名称服务返回是ID,需要替换为国家名称。 但是this.countries值在网格范围内不可用。如何获得网格范围内的值?

对此valueGetter: organismNameGetter.bind(this)进行了尝试,但该按钮不起作用。

2 个答案:

答案 0 :(得分:0)

valueGetter可以通过component

使用 .bind(this) 上下文
valueGetter:  this.countryNameGetter.bind(this)

然后是countryNameGetter-不应该是function内的constructor,而应该是function组件内的this

export class HospiComponent {
    ...
    countryNameGetter (params) {
        console.log(params.data.orgsmId + JSON.stringify(this.organisms));
        return this.countries.filter(item => item.cotryId === params.data.cotryId).name;
    }
    ...
}

但是您必须检查valueGetter的ag-grid生命周期(执行时),以确保在请求数据时数据准备就绪。

答案 1 :(得分:0)

您尝试实现 ag-grid documentation

提供的示例
// in the parent component - the component that hosts ag-grid-angular and specifies which angular components to use in the grid
constructor() {
    this.gridOptions = <GridOptions>{
        context: {
            componentParent: this
        }
    };
    this.gridOptions.rowData = this.createRowData();
    this.gridOptions.columnDefs = this.createColumnDefs();
}

// in the child component - the angular components created dynamically in the grid
// the parent component can then be accessed as follows:
this.params.context.componentParent

您可以阅读有关 ag-grid 上下文的更多信息 here