I know that similar questions have been asked, but I\'ve found none with a good answer. I want to create a select list in an Angular form, where the value for each option is
As value
attribute of option
tag cannot store a whole object we will create a new property id
in the lUsers
array to keep track of the selected item.
HTML :
This will pass the unique id
to our setNewUser
function on change.
In your component.ts :
...
lUsers: any[] = [
{ id: 1, Name: 'Billy Williams', Gender: 'male' },
{ id: 2, Name: 'Sally Ride', Gender: 'female'}
];
curUser: any = this.lUsers[0]; // first will be selected by default by browser
...
setNewUser(id: any): void {
console.log(id);
// Match the selected ID with the ID's in array
this.curUser = this.lUsers.filter(value => value.id === parseInt(id));
console.log(this.curUser);
}
Here is the plnkr demo of the above code. Open your developer tools to view the console logs.