Repository navigation
Closed
Labels
Milestone
Description
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.
- 'Select String' is a simple string-based select, and it works fine.
- '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.
- '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.
- '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.
- '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?
Activity
mhevery commentedon Oct 22, 2015
@vsavkin I think we need to have something like
ng-valueSee: https://github.com/angular/angular.dart/blob/daff0c67adb80ed3305e68cbf9c89ca92ebe9992/lib/directive/ng_model.dart#L674binarious commentedon Nov 16, 2015
Any news on this?
therustmonk commentedon Dec 27, 2015
Maybe problem with
selectvalue holder type? Whystring?https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/select_control_value_accessor.ts
slippyC commentedon Jan 7, 2016
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.erichooshmand commentedon Jan 8, 2016
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.
zoechi commentedon Jan 9, 2016
See also
shotleybuilder commentedon Jan 10, 2016
This works for test case 2:
bar gets displayed on render
selecting foo has
{name:"foo", value:1}returnedOr set
intValue:number = this.objArray[1].value;and thenTo render the name and just return the value.
What doesn't seem to work is setting
strValue:string = this.objArray[1].name;and thenbar 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 ...
benohead commentedon Jan 11, 2016
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' }dougludlow commentedon Jan 19, 2016
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.37 remaining items
mLaird commentedon Jul 13, 2016
ankasala, post your question and your current code at stackoverflow.com
Lots of developers can help you there. This site is for reporting
faults/bugs in Angular2.
On Wed, Jul 13, 2016 at 11:10 AM, ankasala [email protected] wrote:
Mike Laird
12 Arbor Creek Drive, Pittsford, New York 14534
[email protected]
". . . remembering on both sides that civility is not a sign of weakness,
and sincerity is always subject to proof. Let us never negotiate out of
fear, but let us never fear to negotiate." - John F. Kennedy
calvinKG commentedon Oct 5, 2016
Hi,
Guys, have you tried this testing this issues with angular 2 final.
It those not work.
My code:
<select class="form-control" [(ngModel)]="jobRole.userType" required name="userType" #userType="ngModel"> <option *ngFor="let userType of userTypes" [ngValue]="userType">{{userType.description}}</option> </select>My json data:
{"role":{"id":68,"roleName":"TestRole2","description":"View all access pertaining to a users","parentRole":{"id":2,"roleName":"UserProfile","description":"Administer User information and roles","parentRole":"","system":{"id":3,"systemName":"USER_AUTH","description":"FNB Card User Auth","functionPrefix":"UA"},"functions":[{"id":25,"name":"UV","description":"View users","system":{"id":3,"systemName":"USER_AUTH","description":"FNB Card User Auth","functionPrefix":"UA"}},{"id":26,"name":"UA","description":"Administer user information","system":{"id":3,"systemName":"USER_AUTH","description":"FNB Card User Auth","functionPrefix":"UA"}}],"userType":{"id":1,"description":"Staff"}},"system":{"id":3,"systemName":"USER_AUTH","description":"FNB Card User Auth","functionPrefix":"UA"},"functions":[],"userType":{"id":1,"description":"Staff"}}}CaselIT commentedon Oct 5, 2016
@calvinKG just a suggestion.
Try rename the variable in the ngFor so it's not duplicated. eg
<select class="form-control" [(ngModel)]="jobRole.userType" required name="userType" #userType="ngModel"> <option *ngFor="let uT of userTypes" [ngValue]="uT">{{uT.description}}</option> </select>Not sure if it will help.
calvinKG commentedon Oct 5, 2016
@CaselIT I still can't get the selected option .
On my HTML this is what I get.
ChristofDC commentedon Oct 7, 2016
I can't get the selection to work as well.
My html:
The updating of ngModel on selection is working but if I set the selectedOffice variable the option isn't selected in the form control.
jovanialferez commentedon Oct 7, 2016
i got a weird, could be similar, issue where i got a series of selects/dropdowns generated with ngFor. the number of dropdowns varies based on another dropdown. no issue rendering from intial value of the binded variable/model but weird thing is, when you change one value in a dropdown, it reflects as well in the dropdown next to it. the binded model though have the correct updated value. :)
calvinKG commentedon Oct 10, 2016
@CaselIT Managed to do a work around for it. Got selected value.
<select class="form-control"(change)="setSystemsValue($event.target.value)" [(ngModel)]="jobRole.system.id" name="system" #system="ngModel"> <option *ngFor="let s of systems" [value]="s.id" > {{s.systemName}} </option> </select>setSystemsValue(value) { this.jobRole.system = this.systems.filter((currentItem:Systems) => { return currentItem["id"] == value; })[0]; }rkusuma commentedon Nov 21, 2016
I have similar problem too.
When i change the select
state.countryhave the correct value. but when i try to setstate.countrydefault value inngOnInit(state.country = countries[0]) the select will be empty (thecountries[0]not selected)Any solution?
zoechi commentedon Nov 21, 2016
@rkusuma full plunker to reproduce required
rkusuma commentedon Nov 21, 2016
@zoechi sorry it's working now. because i'm using redux, the value that i passing to
ngModelhave different reference.belloyang commentedon Jan 24, 2018
@LMFinney changing [value] to [ngValue] solves the problem for me.
for example:
tluanga34 commentedon Mar 12, 2018
@belloyang Your answer works great. Thanks, you save my day.
janusred23 commentedon Jan 24, 2019
how about, when I select a country, country name will show. And then the country code/zip code will show automatically to the input text box.
<select class="form-control" formControlName="countryId"> <option value="">Select Country</option> <option *ngFor="let country of countries" value={{country.id}}> {{country.name}} </option> </select> <input class="form-control" type="text" formControlName="countryCode"> <!-- Show Country Code/Zip Code -->and in my component file/TS file:
countries: Object[];
getCountry() {
this.countryService.getCountry().subscribe(
resp => {
this.countries = resp['data']['countries'];
}
);
}
I'm just new in Angular, I hope someone can help me. TIA!
angular-automatic-lock-bot commentedon Sep 14, 2019
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.