You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 *ngFor iterates 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 type values later, you just update the groupedProperties array—no changes needed to the template!

内容的提问来源于stack exchange,提问作者user4851126

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:34:42