8000 Hope <select> initialize correctly when ngValue is Object · Issue #13295 · angular/angular · GitHub
[go: up one dir, main page]

Skip to content
Hope <select> initialize correctly when ngValue is Object #13295
Closed
@lonyel

Description

@lonyel

I'm submitting a ... (check one with "x")

[ ] bug report => search github for a similar issue or PR before submitting
[x] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior
When we use <select>, if the list is an Object Array,and the initial ngModel value is set,the Select can't select then correctly item after view inited. eg:

@component({
    selector: 'mycomponent',
   template: '
       <select [(ngModel)]='myItem'>
           <option *ngFor='let item of myItems' [ngValue]='item'>{{item.name}}</option>
      </select>
   '
})
export class mycomponent {
   myItem = {id:2, name: 'lonyel'};
  myItems = [{id: 1,name: 'foo'},{id:2,name: 'lonyel'}];
}

On view is inited, the <select> select null, not 'lonyel'

Expected behavior
We hope the select can select real Business Equal(by id or name) item.

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?
In real business system, the <select>'s items often get from remote db as a Object of array, and the value of NgModel is Object too. So we have to often do transform between id and Object.

We known the issue is cause by looseIdentical:

/** @internal */
  _getOptionId(value: any): string {
    for (const id of Array.from(this._optionMap.keys())) {
      if (looseIdentical(this._optionMap.get(id), value)) return id;
    }
    return null;
  }

So, why do not use JSON.stringify to string like this :

/** @internal */
  _getOptionId(value: any): string {
    for (const id of Array.from(this._optionMap.keys())) {
      if (looseIdentical(JSON.stringify(this._optionMap.get(id)), JSON.stringify(value))) return id;
    }
    return null;
  }

Or add a attrbute to do compare by user like this :

   [track]='track by id' // or $index,$value...propname 

Of course,we can use 3rd component, so the style is not controlled by my app. In the other, we need
encapsulation the BUSINESS Component.

Thanks. (My English is not good enough: <);

Please tell us about your environment:
Windows 10

  • Angular version: 2.2.2

  • Browser: [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ]

  • Language: TypeScript 2.0.10
  • Node (for AoT issues): 6.9.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0