2016-11-03 26 views
7

Tôi đang gặp sự cố này khi đang cố gắng gọi một phương thức dịch vụ trên sự kiện nhấp chuột của nút được tạo bằng cách sử dụng cellRenderer.Lưới điện tử (Góc 2) Không thể truy cập các trường thành phần trong CellRenderer

Tôi đang sử dụng lưới điện với Angular2.

{ headerName: 'Update', field: "update", width: 80, cellRenderer : this.updateRecord } 


updateRecord(params) { 
    var eDiv = document.createElement('div'); 
    eDiv.innerHTML = '<span class="my-css-class"><button class="edit">Edit</button></span>'; 
    var eButton = eDiv.querySelectorAll('.edit')[0]; 
    eButton.addEventListener('click', function() { 
     this.myService.getAll().subscribe(data => console.log(JSON.stringify(data))) 
    }); 
    return eDiv; 
    } 

Tôi nhận được lỗi sau:

EXCEPTION: Cannot read property 'getAll' of undefined 

Ngoài ra, tôi không thể truy cập bất kỳ biến Component tôi.

Trả lời

6

cellRenderer nằm trong ngữ cảnh khác nhau, do đó, this không thể truy cập trong chức năng updateRecord.

Bạn cần khởi tạo thông số context trong gridOptions và sử dụng nó trong đối tượng params.

thiết context trong đối tượng gridOptions bạn theo cách này

this.gridOptions.context = { 
      myService: this.myService 
     } 

myService bạn sẽ có sẵn trong context tài sản.

updateRecord(params) { 
    var eDiv = document.createElement('div'); 
    eDiv.innerHTML = '<span class="my-css-class"><button class="edit">Edit</button></span>'; 
    var eButton = eDiv.querySelectorAll('.edit')[0]; 
    eButton.addEventListener('click', function() { 
     params.context.myService.getAll().subscribe(data => console.log(JSON.stringify(data))) 
    }); 
    return eDiv; 
    } 
+0

Cảm ơn bạn. Làm việc hoàn toàn ổn. –

Các vấn đề liên quan