Angular 18 hack for <select> with <input> in Signal() way to be optimized

Discussão em 'Angular' iniciado por Juergen, Novembro 17, 2024.

  1. Juergen

    Juergen Guest

    I have a hack to implement a select box with dynamic set and by double click to have this selection box with a indecently input box. The added new options will not double (by a Set) be sorted and at least available for the selection box options.

    the code will be:

    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.update(items => { return[ ...items, 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


    For more details, please refer to stackblitz:

    https://stackblitz.com/edit/stackblitz-starters-r9ar8j?file=src/main.ts

    However, I am sure, that hack could be optimized. I looking fromward to your kind comments.

    Continue reading...

Compartilhe esta Página