如何在Angular 4中编写加载函数?附复选框树组件代码
How to Implement a Load Function for Angular 4 Checkbox Tree Component
Hey there! Let's walk through how to add a proper load function for your Angular 4 checkbox tree component using Syncfusion's TreeView. We'll adjust your existing code to support both local simulated async loading and API-driven data fetching.
Step 1: Update the Component Class (ang.component.ts)
First, we'll add lifecycle hooks, a TreeView reference, and the load function to handle data initialization. Here's the revised code with explanations:
import { Component, OnInit, ViewChild } from '@angular/core'; import { TreeViewComponent } from '@syncfusion/ej2-ng-navigations'; import { HttpClient } from '@angular/common/http'; // Import if using API data @Component({ selector: 'app-checkboxes', templateUrl: './checkboxes.component.html' }) export class CheckboxesComponent implements OnInit { @ViewChild('treeelement') treeViewObj: TreeViewComponent; // Access TreeView instance public countries: Object[] = []; public field: Object = { id: 'id', parentID: 'pid', text: 'name', hasChildren: 'hasChild' }; public showCheckBox: boolean = true; public checkedNodes: string[] = ['2', '6']; // Inject HttpClient if fetching from API constructor(private http: HttpClient) { } ngOnInit(): void { // Trigger data load when component initializes this.loadTreeData(); } // Core load function for tree data private loadTreeData(): void { // Option 1: Simulate async local loading (mimics API delay) setTimeout(() => { this.countries = [ { id: 1, name: 'Australia', hasChild: true, expanded: true }, { id: 2, pid: 1, name: 'New South Wales', isChecked: true }, { id: 3, pid: 1, name: 'Victoria' }, { id: 4, pid: 1, name: 'South Australia' }, { id: 6, pid: 1, name: 'Western Australia', isChecked: true }, { id: 7, name: 'Brazil', hasChild: true }, { id: 8, pid: 7, name: 'Paraná' }, { id: 9, pid: 7, name: 'Ceará' }, { id: 10, pid: 7, name: 'Acre' }, { id: 11, name: 'China', hasChild: true }, { id: 12, pid: 11, name: 'Guangzhou' }, { id: 13, pid: 11, name: 'Shanghai' }, { id: 14, pid: 11, name: 'Beijing' }, { id: 15, pid: 11, name: 'Shantou' }, { id: 16, name: 'France', hasChild: true }, { id: 17, pid: 16, name: 'Pays de la Loire' }, { id: 18, pid: 16, name: 'Aquitaine' }, { id: 19, pid: 16, name: 'Brittany' }, { id: 20, pid: 16, name: 'Lorraine' }, { id: 21, name: 'India', hasChild: true }, { id: 22, pid: 21, name: 'Assam' }, { id: 23, pid: 21, name: 'Bihar' }, { id: 24, pid: 21, name: 'Tamil Nadu' }, { id: 25, pid: 21, name: 'Punjab' } ]; // Update TreeView data and refresh to reflect changes this.treeViewObj.fields.dataSource = this.countries; this.treeViewObj.refresh(); }, 500); // Simulate network latency // Option 2: Load data from an API (uncomment to use) /* this.http.get('your-api-endpoint/tree-data').subscribe((data: Object[]) => { this.countries = data; this.treeViewObj.fields.dataSource = this.countries; this.treeViewObj.refresh(); // Reassign checked nodes if needed after data loads this.checkedNodes = ['2', '6']; }); */ } }
Key Changes Breakdown:
- Added
OnInitinterface andngOnInithook to trigger data load when the component mounts. - Used
@ViewChildto get a direct reference to the TreeView component, allowing us to update its data source and refresh it post-load. - Created
loadTreeData()to handle two common loading scenarios:- Local Simulated Load: Uses
setTimeoutto mimic async behavior (like waiting for an API response). - API Load: Uses Angular's
HttpClientto fetch remote data (don't forget to importHttpClientModulein your app module if using this option).
- Local Simulated Load: Uses
- Removed
dataSourcefrom the initialfieldobject to update it dynamically after data loads.
Step 2: Update the Template (ang.component.html)
Add a template reference variable to the TreeView so we can access it in the component:
<p>Angular 4 Checkbox Tree</p> <div id='treeparent'> <ej-treeview #treeelement id='treeelement' [fields]='field' [showCheckBox]='showCheckBox' [checkedNodes]='checkedNodes'> </ej-treeview> </div>
Quick Setup Note (for API Option):
If you're fetching data from an API, make sure to import HttpClientModule in your AppModule:
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ // ... other existing imports HttpClientModule ] }) export class AppModule { }
Bonus Tips:
- Lazy Loading: If you want to load child nodes only when a parent is expanded, enable Syncfusion's
loadOnDemandproperty and hook into thenodeExpandingevent to fetch child data dynamically. - Loading States: Add a spinner or loading message in your template that's hidden once the data finishes loading (use a boolean flag in the component to toggle visibility).
内容的提问来源于stack exchange,提问作者Ajith Deivam
相关产品推荐
相关产品推荐

