Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-zorro cascader lazy load data, nzLoadData function got this=undefined

I want to lazy load data for cacader. But failed because in the load function this=undefined. The function is defined in component, and other functions in the component working well. Please help, thanks.

<nz-cascader  
  \[nzLoadData\]\="loadCityBuildingData"  
  \[(ngModel)\]\="selectedLocation"  
  (ngModelChange)\="onNewLocationModalChanges($event)"  
\> </nz-cascader>
loadCityBuildingData(node: NzCascaderOption, index: number): PromiseLike<void\> {  
  console.log(this);  

 return new Promise(resolve => {  
    if (index < 0) {  
      this.cityService.getCities().subscribe(item => {  
        const cities = \[\];  
  item.forEach(city => {  
          cities.push({value: city.id, label: city.name});  
  });  
  node.children \= cities;  
  resolve();  
  });  
  } else if (index === 0) {  
      this.buildingService.getBuildingsByCityId(node.value).subscribe(item => {  
        const buildings = \[\];  
  item.forEach(building => {  
          buildings.push({value: building.id, label: building.name, isLeaf: true});  
  });  
  node.children \= buildings;  
  resolve();  
  });  
  }  
  });  
}
like image 650
ZhaoGuoXin Avatar asked Feb 02 '26 02:02

ZhaoGuoXin


2 Answers

My name's Wendell and I am the author of the component. ;)

This is a frequestly asked question. The reason is that:

  1. When you pass loadCityBuildingData to nzLoadData, loadCityBuildData becomes a property of NzCascaderComponent.
  2. When the cascader calls this method (by calling nzLoadData actually), this in loadCityBuildingData is bound to nothing.
  3. So you have to bind this in loadCityBuildingData before you pass it.
    1. You could use arrow function.
    2. You could use Function.bind.
like image 106
hullis Avatar answered Feb 04 '26 14:02

hullis


A solution I found that works for me is to define your function like following :

loadCityBuildingData = (node: NzCascaderOption, index: number): PromiseLike<void> => {
    ...your code 
}
like image 20
Hugo Ribiere Avatar answered Feb 04 '26 15:02

Hugo Ribiere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!