9/30/2018 Comments Form select elements in angular
As web developers we have been developing web forms almost on every app. How many times have you spent time searching on google (or bing - no offense ) on finding solutions to pre-select an option on a select control while using angular? Yeah I know! Many times. And when you read the solution you are like "Ohh yess!"
Let's demystify this Create a simple form
If you run this example and you interpolate the {{selectedItem}}, you would expect to get an item object but instead you get the result of the <option>.
You need to tell angular explicitly what you want to get as a selected value
You should tell angular what the value would be. This would happen if you make use of the ngValue directive. Simple as that
Pre-select an option
So far so good?
You now want to load the html and see the value that you got from the server's api in the select control. I guess that you've tried to set in selectedItem an id of the items array, or you've even tried to assign a complete object of the array. But still, you can not pre-select an item. The recipe for this is to use a reference of the same array
Even if you get the data from an API, you should always get the reference from the array of items you bound in select control.
You can find here a complete example https://stackblitz.com/edit/simple-form-select-elements
Comments
|
AuthorI am an Angular GDE, content creator who loves sharing knowledge TagsAll Angular Angularjs General Graphql Ionic Javascript .net Nodejs Typescript |