Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defaulting an Angular2 <option> in a <select> with two-way binding

Tags:

angular

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> 
like image 844
mariocatch Avatar asked Apr 14 '16 17:04

mariocatch


People also ask

Does angular2 support 2 way binding?

Angular v2+ supports two-way data binding using ngModel directive and also by having getter and setter methods.

What is used for two way data binding in angular2?

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.

Is ngModel necessary for two way 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.


1 Answers

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> 
like image 108
Mark Rajcok Avatar answered Oct 16 '22 06:10

Mark Rajcok