I'd like to setup a <select>
with a default <option>
using HTML, and populating the rest of the <select>
with two way binding to my model.
HTML:
<select class="form-control" required [(ngModel)]="model.product" ngControl="product"> <option value="">Select a product</option> <option *ngFor="#product of products" [value]="product">{{product}}</option> </select>
Model:
products: string[] = [ 'Foo', 'Bar' ];
What's happening now is my the select is binding to the model, which is:
model: Entry = new Entry();
So, there's no default value in the product
property, thus the <select>
binds to nothing. I mean, this is working as expected.
I'm trying to figure out how to get a default value to show up in the <select>
though, and I'd like to do that without hard coding a UI value in my model and defaulting that in a new instance of my model. Does Angular 2 have a way to deal with this?
Edit:
The result HTML should look like:
<select> <option value>Select a product</option> <option value="foo">Foo</option> <option value="bar">Bar</option> </select>
Angular v2+ supports two-way data binding using ngModel directive and also by having getter and setter methods.
two-way data binding in angular 2 is supported using the event and the property binding. we can use ngmodel directive to use two-way data binding.
Because no built-in HTML element follows the x value and xChange event pattern, two-way binding with form elements requires NgModel . For more information on how to use two-way binding in forms, see Angular NgModel.
I don't think Angular has a way to deal with this. You'll have to do some work:
<select class="form-control" required [(ngModel)]="model.product"> <option *ngFor="#product of [defaultStr].concat(products)" [value]="product === defaultStr ? null : product"> {{product}} </option> </select>
defaultStr = 'Select a product'; model = { product: null }; products: string[] = [ 'Foo', 'Bar' ];
Plunker
Since you are using NgModel to bind the selected value, you have to set the bound property to the default value initially, which is null
, otherwise that option won't be selected by default:
model = { product: null };
With null
, I noticed that the HTML is
<option value="null">Select a product</option>
So, you may prefer to use an empty string ''
instead of null
:
[value]="product === defaultStr ? '' : product"
model = { product: '' };
Then the HTML is
<option value="">Select a product</option>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With