Angular 4中用单个ngFor循环在select标签展示两个独立optgroup
Solution: Group Data for Single Optgroup Loop
To display your historyOfWords data in two <optgroup> elements using a clean, maintainable approach (with a single outer loop for optgroups), follow these steps:
Step 1: Prepare Grouped Data in Your Component
First, create a computed property that groups your original data into the two categories you need. This keeps your template clean and avoids duplicate logic:
// In your Angular component class historyOfWords = [ { 'property': 'property1', 'type': 'dataprop', 'value': 'value1' }, { 'property': 'Ref1', 'type': 'objprop', 'value': 'Prop of Ref1' } ]; // Group data into optgroup-friendly structure get groupedProperties() { return [ { label: 'Properties', items: this.historyOfWords.filter(item => item.type !== 'objprop') }, { label: 'Object References', items: this.historyOfWords.filter(item => item.type === 'objprop') } ]; }
Step 2: Update the Template with Single Optgroup Loop
Now use a single *ngFor loop to generate both <optgroup> elements, with an inner loop for the options inside each group:
<select size="10"> <!-- Single ngFor to create each optgroup --> <optgroup *ngFor="let group of groupedProperties" [label]="group.label"> <!-- Inner loop for options in the current group --> <option *ngFor="let item of group.items" [value]="item.property"> {{ item.property }}: {{ item.value }} </option> </optgroup> </select>
Why This Works:
- The outer
*ngForiterates over your grouped data to create each<optgroup>with the correct label. - The inner loop handles generating options for each category, keeping your template DRY (Don’t Repeat Yourself).
- If you ever add new
typevalues later, you just update thegroupedPropertiesarray—no changes needed to the template!
内容的提问来源于stack exchange,提问作者user4851126
相关产品推荐
相关产品推荐

