Initially loading of an existing option fails

2020-05-05 18:08发布

问题:

The initially loading (of an existing iu.unit) fails:

 <select id="unit" name="unit" #unit="ngModel" class="form-control" 
     [(ngModel)]="iu.unit" (change)="onDropdownChangeUnit(rec,iu)">
     <option *ngFor="let i of UI_Units" [ngValue]="i">{{i.name}}</option>
 </select>

It shows me all unit's from UI_Units, but it doesn't show the initial value of iu.unit.

What did I d wrong ?

Updated

Structure, I go with a foreach over all ingridientUnit => iu, try to assign it with it's initial value.

But when the user wants to change that - UI_Units => coming from backend(asp.net Core) - it should be reassigned to iu.unit.

export class Recipe{

    id: string;

    ingridientUnit: IngridientUnit[] // iu

    // ...
}


export class IngridientUnit {

    id: string;

    unit: Unit[]

    // ...
}

export class Unit {

    id: string;
    name: string;

    // ...
}

Fetching from server:

 getUnits(filter: ServerRequest) {
    return this._http.get(this.myAppUrl + 'Unit/GetUnits' + '?' + this.toQueryString(filter))
        .pipe(map((res: Unit[]) => { return res; }));
}

回答1:

First of all, select only shows its children options in the dropdown.

Following that reason, iu.unit must be in UI_Units or nothing will be selected by default and the option of iu.unit will not appear in the list.

We can check Angular Forms' code on this, I'd like to direct you focus to line 134 writeValue and line 178 _getOptionId,

writeValue(value: any): void {
  this.value = value;
  const id: string|null = this._getOptionId(value);
  // excerpt only
}

_getOptionId(value: any): string|null {
  for (const id of Array.from(this._optionMap.keys())) {
    if (this._compareWith(this._optionMap.get(id), value)) return id;
  }
  return null;
}

writeValue is called when a value is passed into the element with ngModel, the value is then looked up in a map containing all the child options. If an option representing the value (in your case iu.unit) isn't found, nothing meaningful will happen.

Most importantly, the option would not appear by default under the select element, it will appear only when it's explicitly included in your template.

I've created a working example of what you're trying to accomplish, note that iu.unit is an element in the array UI_Units. That's how its comparison algorithm work.