Search code examples
angularcombobox

A combobox extracts a code from event.target.value: it shouldn't, a code isn't replaced by a label when expected. I'm not doing things the proper way


I have an application that works but shouldn't. And I would like starting correcting it.
I believe I have done things that clashes one against another, because my knowledge of Angular is low.

  1. By a REST service, Angular receives Commune (City) objects, with their name, population, city code, etc.
/** Une commune du Code Officiel Géographique */
export interface Commune { 
    /** Code de la commune */
    codeCommune: string;

    /** Nom de la commune */
    nomCommune: string;

    /** Population totale de la commune. */
    population: number;

    /** Surface de la commune, en hectares. N\'est pas alimenté pour les arrondissements. */
    surface?: number | null;
    [...]
}

enter image description here

I'm displaying and offer to select a value by this combo-box:

<input type="text" list="communesCOG" [(ngModel)]="libelleCommuneSelectionnee" (change)="selectCommune($event.target.value)" placeholder="Tapez le nom de la commune">
<datalist id="communesCOG" >
    <option *ngFor="let commune of communes" [value]="commune.codeCommune">{{commune.nomCommune}} ({{commune.nomDepartement}})</option>
</datalist>

It doesn't stop my application, but my IDE is already complaining about that:

enter image description here

selectCommune($event.target.value), with value in red, that isn't recognized.

What surprises me, is that it is working: the code 55001 enters my function:
(where communesMap is a communesMap: Map<string, Commune> = new Map<string, Commune>() loaded with all the French cities, and indexed by their city code).

enter image description here

but there's no value property for an Event.target... What should have done, here?

  1. If I select a value in that list, I'm expecting a formatted result shown in that combobox, as I do not wish the user to see the city code that won't mind anything to him.

But at the time I'm doing the selection, and until I leave the field, it only displays the city code:

enter image description here

  1. And then, the focus left, displays the wished description:
    Abainville (Meuse) 300 hab.

enter image description here


Solution

  • There is an [(ngModel)] on your input. Do not subscribe to (change) event, but to (ngModelChange) instead, where $event is the new value:

    <input type="text" list="communesCOG" [(ngModel)]="libelleCommuneSelectionnee" (ngModelChange)="selectCommune($event)" placeholder="Tapez le nom de la commune">