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
#angular #drop down binding #ngfor #products