I recently found out that there is an alternative for the value property in the OPTION part for SELECT, namely ngValue . The docs about this are missing (all I could find: https://angular.io/docs/ts/latest/api/forms/index/NgSelectOption-directive.html ). Anyway, the idea is that when you use an object for ngModel you can use ngValue and it works well. Otherwise, just for example. ID is updated. If we have only an array of strings, a value is sufficient. Here are some examples:
{{myModel | json}} <select [(ngModel)]="myModel"> <option *ngFor="let i of items" [ngValue]="i">{{i.value}}</option> </select> <br /><br /> {{mySimpleModel}} <select [(ngModel)]="mySimpleModel"> <option *ngFor="let i of simpleItems" [value]="i">{{i}}</option> </select>
While this works as expected, there are distinctive differences between them: when using ngValue predefined value is not selected in the drop-down list, while for primitive types this value is selected at boot time. For instance:.
items: any[] = [{id: 1, value: 'item1'}, {id: 2, value: 'item2'}, {id: 3, value: 'item3'}]; myModel: any = {id: this.items[1].id , value: this.items[1].value}; simpleItems: string[] = ['item1', 'item2', 'item3']; mySimpleModel: string = this.simpleItems[1];
See an example here: https://plnkr.co/edit/JBrtmx7QkPZztBjaqYkS?p=preview So why does Angular set a default value for strings, but not for objects? And what is the most elegant workaround?
source share