Angular

Last Updated: 8/30/2023

Working with Dropdown

  • Apply ngModel and set name
  • We don't hardcode the options instead we call an API on the server to get the list of options and then populate the dropdown list dynamically
  • In options name is shown to the user, id is sent to the server for persistence
  • In real world app we don't want a value to selected by default, we want to have an empty option and enforce user to make selection
  • Most of the times we send value to the server and option value can only be string in html
contactMethods = [
	{id: 1, name: 'Email'}
	{id: 2, name: 'Phone'}
]
<select ngModel name="contactMethod" id="contactMethod" class="form-control">
	<option value=""></option>
	<option *ngFor="let method of contactMethods" [value]="method.id">{{method.name}}</option>
</select>

Option value as Selected object

  • Sometimes we want to set the property to the actual object
  • Use ngValue attribute directive to bind to complex object
<option *ngFor="let method of contactMethod" [ngValue]="method">{{method.name}}</option>
  • For multiple options, add multiple attribute and value in formcontrol will be array.