angular icon indicating copy to clipboard operation
angular copied to clipboard

How to use select/option/NgFor on an array of objects?

Open LMFinney opened this issue 11 years ago • 47 comments

I'm having trouble creating a select in Angular2 that is backed by an array of Objects instead of strings. I knew how to do it in AngularJS using ngOptions, but it doesn't seem to work in Angular2 (I'm using alpha 42).

In the sample below, I have five selects, but only three of them work.

  1. 'Select String' is a simple string-based select, and it works fine.
  2. 'Select Object via 2-way binding' was my attempt to use 2-way binding. Unfortunately, it fails in two ways - when the page loads, the select shows the wrong value (foo instead of bar), and when I select an option in the list, the value '[object Object]' gets sent to the backing store instead of the correct value.
  3. 'Select Object via event' was my attempt to get the selected value from $event. It fails in two ways, too - the initial load is incorrect in the same way as (2), and when I selection an option in the list, the value '[object Object]' is retrieved from the event, so I can't get the right value. The select gets cleared.
  4. 'Select Object via string' is an approach that uses an object that works. Unfortunately, it really works by using the string array from (1) and converting the value from string to object and back.
  5. 'Select Object via JSON' might be a bit better than (4) because it doesn't require the string array, but it does involve using JSON each way. Also, I'm not sure if getting the Event from (change) is better or worse than getting the stringified objected from (ng-model-change). (@Chocoloper helped me with this version)
import {Component, FORM_DIRECTIVES, NgFor, Inject} from 'angular2/angular2';
import {RouteParams} from 'angular2/router';

interface TestObject {
  name:string;
  value:number;
}

@Component({
  selector: 'app',
  template: `<h4>Select String</h4>
            <select [(ng-model)]="strValue">
                <option *ng-for="#o of strArray" [value]="o">{{o}}</option>
            </select>

            <h4>Select Object via 2-way binding</h4>
            <select [(ng-model)]="objValue1">
                <option *ng-for="#o of objArray" [value]="o">{{o.name}}</option>
            </select>

            <h4>Select Object via event</h4>
            <select [ng-model]="objValue2" (change)="updateObjValue2($event)">
                <option *ng-for="#o of objArray" [value]="o">{{o.name}}</option>
            </select>

            <h4>Select Object via string</h4>
            <select [ng-model]="objValue3.name" (change)="updateObjValue3($event)">
                <option *ng-for="#o of strArray" [value]="o">{{o}}</option>
            </select>

            <h4>Select Object via JSON</h4>
            <select [ng-model]="stringify(objValue4)" (ng-model-change)="updateObjValue4($event)">
                <option *ng-for="#o of objArray" [value]="stringify(o)">{{o.name}}</option>
            </select>

            <div><button (click)="printValues()">Print Values</button></div>`,
  directives: [FORM_DIRECTIVES, NgFor]
})
export class AppComponent {
  objArray:TestObject[] = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
  objValue1:TestObject = this.objArray[1];
  objValue2:TestObject = this.objArray[1];
  objValue3:TestObject = this.objArray[1];
  objValue4:TestObject = this.objArray[1];

  strArray:string[] = this.objArray.map((obj:TestObject) => obj.name);
  strValue:string = this.strArray[1];

  stringify(o:any):string {
    return JSON.stringify(o);
  }

  updateObjValue2(event:Event):void {
    const value:string = (<HTMLSelectElement>event.srcElement).value;

    this.objValue2 = this.objArray.find((obj:TestObject) => obj.name === value);
  }

  updateObjValue3(event:Event):void {
    const value:string = (<HTMLSelectElement>event.srcElement).value;

    this.objValue3 = this.objArray.find((obj:TestObject) => obj.name === value);
  }

  updateObjValue4(event:string):void {
    this.objValue4 = JSON.parse(event);
    // if there were functions on TestObject, JSON.parse wouldn't be enough; we'd need this:
    //this.objValue4 = this.objArray.find((obj:TestObject) => obj.name === JSON.parse(event).name);
  }

  printValues():void {
    console.log('strValue', this.strValue);
    console.log('objValue1', this.objValue1);
    console.log('objValue2', this.objValue2);
    console.log('objValue3', this.objValue3);
    console.log('objValue4', this.objValue4);
  }
}

I can do (4) or (5) if that's the intended way, but they seem pretty clunky. Is there another approach? Am I just too early in the alpha? Did I do something silly?

LMFinney avatar Oct 21 '15 00:10 LMFinney

@vsavkin I think we need to have something like ng-value See: https://github.com/angular/angular.dart/blob/daff0c67adb80ed3305e68cbf9c89ca92ebe9992/lib/directive/ng_model.dart#L674

mhevery avatar Oct 22 '15 19:10 mhevery

Any news on this?

binarious avatar Nov 16 '15 14:11 binarious

Maybe problem with select value holder type? Why string?

export class SelectControlValueAccessor implements ControlValueAccessor {
  value: string;   // Does typescript has any convert rules?
  onChange = (_) => {};
  onTouched = () => {};
...
  writeValue(value: any): void {
    this.value = value;
    this._renderer.setElementProperty(this._elementRef, 'value', value);
  }

https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts

therustmonk avatar Dec 27 '15 21:12 therustmonk

I have run into this problem as well. NgFor does not seem to work correctly inside a <select> tag. Was attempting to loop through an array of state abbreviations.

slippyC avatar Jan 07 '16 08:01 slippyC

We're experiencing this too. We'd like to be able to use ngFor inside of a select and access the object representing the option when it's selected.

erichooshmand avatar Jan 08 '16 22:01 erichooshmand

See also

  • http://stackoverflow.com/questions/34686855/angular2-access-a-select-event-change-within-the-component
  • http://stackoverflow.com/questions/33181936/how-to-use-select-option-ngfor-on-an-array-of-objects-in-angular2

zoechi avatar Jan 09 '16 15:01 zoechi

This works for test case 2:

<select [(ngModel)]="objValue.name">
<option *ngFor="#oo of objArray" [value]="oo.name">{{oo.name}}</option>
</select>

bar gets displayed on render selecting foo has {name:"foo", value:1} returned

Or set intValue:number = this.objArray[1].value; and then

<select [(ngModel)]="intValue">
<option *ngFor="#oo of objArray" [value]="oo.value">{{oo.name}}</option>
</select>

To render the name and just return the value.

What doesn't seem to work is setting strValue:string = this.objArray[1].name; and then

<select [(ngModel)]="strValue">
  <option *ngFor="#oo of objArray" [value]="oo.name">{{oo.name}}</option>
</select>

bar gets rendered, but strValue is strangely now an object {name:"bar",value:1} and selecting foo doesn't change the value of strValue (probably because it's an object)

The [(ng-model)] syntax was throwing errors for me. I'm new to ng-2 ...

shotleybuilder avatar Jan 10 '16 10:01 shotleybuilder

Actually, wouldn't setting [(ngModel)] to "objValue.name" change the name of objValue and not change the selected object when the user chooses another entry in the select box? i.e.:

initial: objArray = [ { 'name':'name1' }, { 'name':'name2' } ] objValue = { 'name':'name1' }

after selecting the second entry: objArray = [ { 'name':'name2' }, { 'name':'name2' } ] objValue = { 'name':'name2' }

benohead avatar Jan 11 '16 13:01 benohead

Test case 2 seems logical to me, but still doesn't work in beta.1. The value appears to be converted to a string, which results in [object Object]. I'm attempting to implement some cascading dropdowns, being able to use objects as the value would make this much easier.

dougludlow avatar Jan 19 '16 22:01 dougludlow

While looking at the angular2 tutorial I came across this bug while playing with the sample code https://angular.io/resources/live-examples/forms/ts/plnkr.html It is working on chrome 49 but not on firefox 45 and edge 25.

CaselIT avatar Feb 03 '16 11:02 CaselIT

+1

eliezerreis avatar Feb 11 '16 00:02 eliezerreis

So we can't use select. Maybe we should use radio buttons. Oh , no wait, those are broken too

GregWoods avatar Feb 17 '16 11:02 GregWoods

Of course you can use select, it's just not as easy as wanted / expected. I use a string property in my component now for 2 way binding to the view, and an additional change listener which picks the corresponding object from the list of available objects.

Snippets:

private repositories: Repository[];
private selectedRepositoryName: string;
private selectedRepository: Repository;

private onRepositorySelected() {
    this.selectedRepository = this.repositories.find(repository => repository.name === this.selectedRepositoryName);
}
<select [(ngModel)]="selectedRepositoryName" (ngModelChange)="onRepositorySelected()">
    <option *ngFor="#repository of repositories" [value]="repository.name">{{repository.name}}</option>
</select>

slintes avatar Feb 17 '16 12:02 slintes

I could not get the above hack from @slintes to work at first. Interesting to note that the order of the ngModel and the ngModelChange is important. For reference, we are using 2.0.0-beta.3.

jondejong avatar Feb 18 '16 00:02 jondejong

I confirm that [(ngModel)] and (ngModelChange) on select are not working in Firefox and Edge. Any plans on fixing this?

Lanayx avatar Feb 23 '16 13:02 Lanayx

oh no, you're right, I only tested in Chrome until now.

slintes avatar Feb 23 '16 16:02 slintes

The Firefox and IE select bug is a separate issue: https://github.com/angular/angular/issues/6573

binarious avatar Feb 23 '16 16:02 binarious

I think this issue may cause by the two-way binding when we set <option *ngFor="#level of levels" [value]="level">{{level.name}}, the html option's value is actually not the value of the item from the *ngFor loop.

DanielYKPan avatar Mar 05 '16 10:03 DanielYKPan

@slintes , thanks a lot for the workaround.

vvolodin avatar Mar 07 '16 11:03 vvolodin

Any updates on when this is going to get fixed?

ObaidUrRehman avatar Mar 14 '16 11:03 ObaidUrRehman