Thursday, October 18, 2018

angular - Defaulting an Angular2 in a with two-way binding



I'd like to setup a with two way binding to my model.



HTML:







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 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'
];


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







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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...