Angular初始化时如何填充关联依赖的下拉列表?
Hey there! The issue here is that your second select's options aren't being loaded on initial load because the selectGroup method (which triggers getDestinationTo) only runs when you click the first select, not when the initial destinationfromCode value is set. Here's how to fix it:
Step 1: Trigger the second select load after initializing the first select's options
Once your groupDestinations are fetched, if there's already a preselected destinationfromCode in orderTracking, you need to call selectGroup with that value to load the second select's options. Update your getGroupDestitantion method:
getGroupDestitantion(): void { let path: string = '/uomback/rdestinationgroup/code-displayname'; this.restService.get(path).subscribe(response => { this.groupDestinations = response['payload']; // Load second select if initial value exists if (this.orderTracking.destinationfromCode) { this.selectGroup(this.orderTracking.destinationfromCode); } }); }
Step 2: Use ngModelChange instead of click for reliable updates
Relying on the click event isn't ideal because it can trigger even if the user doesn't change the selection. Instead, use ngModelChange to call selectGroup whenever the first select's value changes (including programmatic changes):
Update your first select template:
<select [ngModel]="orderTracking.destinationfromCode" (ngModelChange)="onDestinationFromChange($event)" > <option value=""></option> <option *ngFor="let destination of groupDestinations" [ngValue]="destination.code"> {{destination.displayname}} </option> </select>
Add this method to your component TS:
onDestinationFromChange(selectedCode: string): void { this.orderTracking.destinationfromCode = selectedCode; this.selectGroup(selectedCode); // If your original `modelChanged` method had other logic, include it here }
Step 3: Handle cases where orderTracking loads after groupDestinations
If orderTracking is fetched asynchronously (e.g., from another API call), make sure to call selectGroup once both orderTracking and groupDestinations are ready. For example, if you fetch orderTracking in ngOnInit:
ngOnInit(): void { this.getGroupDestitantion(); this.fetchOrderTracking().subscribe(order => { this.orderTracking = order; // Only call selectGroup if groupDestinations are already loaded if (this.groupDestinations?.length) { this.selectGroup(this.orderTracking.destinationfromCode); } }); }
Why this works:
- When the component initializes, after loading the first select's options, we immediately check if there's a preselected value and load the second select's options.
- Using
ngModelChangeensures that whenever the first select's value changes (whether by user interaction or code), the second select is updated correctly.
This should make both selects populate on initial load if orderTracking.destinationfromCode has a value, and keep them in sync when the user changes the first select.
内容的提问来源于stack exchange,提问作者None

