I'd like to setup a with a default using HTML, and populating the rest of the with two way binding to my model.
HTML:
[(ngModel)]="model.product"
ngControl="product">
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 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 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:
Answer
I don't think Angular has a way to deal with this. You'll have to do some work:
defaultStr = 'Select a product';
model = { product: null };
products: string[] = [
'Foo',
'Bar'
];
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
So, you may prefer to use an empty string '' instead of null:
[value]="product === defaultStr ? '' : product"
model = { product: '' };
Then the HTML is
No comments:
Post a Comment