Angular Drop Down Binding
December 11, 2015
angulartypescript
Binding to drop downs is always interesting. Here’s an example in Angular 2 …
Template
Let’s look at the template first in our component.
- On line 5, we use a NgFor to list the drop down options, looping over a products array in our model and making use of a product local variable.
- We use a property binding to bind the drop down option value to the product id.
- We use interpolation to bind the drop down option text to the product name
- On line 4, we use an event binding to handle setting the selected product when the drop down selection changes
- On line 7, we use interpolation again to output the selected product name
@Component({
selector: 'my-dropdown',
template: `
<select (change)="onSelect($event.target.value)">
<option *ngFor="#product of products" [value]="product.id">{{product.name}}</option>
</select>
<div>selection={{selectedProduct.name}}</div>
`,
directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})
Code
Let’s look at the code now …
Firstly we need a class to define a product …
class Product {
id: number;
name: string;
}
We can now define the class for our drop down component …
- On line 2, we’ve hardcoded an array of products for this demo
- On line 7, we have a property selectedProduct to hold the selected product which is initialised to the first product
- On line 8, we have an onSelect method which handles when a drop down option is selected which in tern sets the selectedProduct property
class DropDownComponent {
public products: Product[] = [
{ id: 1, name: "Table" },
{ id: 2, name: "Chair" },
{ id: 3, name: "Light" }
];
public selectedProduct: Product = this.products[0];
onSelect(productId) {
this.selectedProduct = null;
for (var i = 0; i < this.products.length; i++) {
if (this.products[i].id == productId) {
this.selectedProduct = this.products[i];
}
}
}
}
Is there a simpler way of handling the selected product? Is there a directive that could replace the onSelect()
method in the component code?
Comments
Arun November 16, 2017
Wonderful Example… I liked the way you have put here in simple angular terms. Appreciate the work.
Shervin February 11, 2019
Great, but what if we have a reset button? will it’s value return to default?
Nagendra May 15, 2019
nice Example….
If you to learn more about TypeScript, you may find my free TypeScript course useful:
Learn TypeScript
You might find some of my other posts interesting: