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

Angular 18基于Signal实现的Select+Input组合方案优化诉求

带动态集合的Select组件优化需求

我临时实现了一个带动态集合的select组件,核心功能如下:

  • 双击可在select下拉框和独立输入框之间切换
  • 新增选项通过Set去重、排序后加入可选列表

以下是实现代码:

import { Component, signal } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    FormsModule
  ],
  template: `
    <h1>Selectbox with Input Option</h1>
    
    <p> select / input-box will toggle by double click </p>
    <p> input value will be take over by leaving the input box </p>
    @if (!isInput()){
    <select
      (dblclick)="isInput.set(!isInput())"
      [ngModel]="selectItem()"
      (change)="onSelectChange($any($event.target).value)">
      @for (item of OptionValue(); track item) {
        <option>
          {{ item }}
        </option>
      }
    </select>} @else {
      <input
        (dblclick)="isInput.set(!isInput())"
        [ngModel]="selectItem()"
        (focusout)="onSelectChange($any($event.target).value)">
    }
    <hr>

    <p>show selected item:    {{selectItem()}}</p>

    <hr>
  `,
})
export class App {
  name = 'Select with Input';

  public selectItem = signal('A');
  public OptionValue = signal(new Set<string>(['A','B','C']));
  protected isInput = signal(false)

  onSelectChange(item:string){
    this.selectItem.set(item);
    this.OptionValue().add(item);
    const OptionValueAy = Array.from(this.OptionValue()).sort();
    this.OptionValue().clear()
    OptionValueAy.forEach(item => this.OptionValue().add(item))
  }
} //end of class

我认为该临时方案存在不少优化空间,恳请各位提供专业的优化建议。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 08:14:53