How to assign selected value to "Select" when value is of class object in angular 2 - angular2-template

Using angular 2.2.4 from following links learned select list of class object:
How can I get new selection in "select" in Angular 2?
https://stackoverflow.com/a/35945293/4773561
Angular 2 Dropdown Options Default Value
& implemented as follows
<select id="st" name="state" [(ngModel)]="selectedState" (ngModelChange)="onStateSelectedForVanue($event)">
<option *ngFor="let state of states"
[ngValue]="state">{{state.name}}
</option>
</select>
here 'states' is list of State Class object
export class State {
public id:number;
public name:string;
}
this is list of class
public states : State[]= [];
for states getting value from Service,up to this code I get drop-down of 'state-name'.Now I want to show 'Default' of 'Pre-selected' State.For that created selectedState Class Object and assign through [(ngModel)] or [ngModel]
public selectedState: State;
in constructor follwing value assign:
this.selectedState = new State();
this.selectedState.id = 12;
this.selectedState.name = 'Goa';
and states list getting from ngOnInit() but default, no list item(state) is getting selected
also tried adding following code in
<option></option>
[selected]="state.name === selectedState.name" with reference link
Set initially selected item in Select list in Angular2
https://stackoverflow.com/a/37666951/4773561
https://stackoverflow.com/a/37663411/4773561
still not getting pre-selected state
what is wrong in code ?

Related

Cant pass value from one view model to another in aurelia

I have two views, in view two i have a select option in which if the user selects an option i would want it to be passed to view one.
this is what i tried
view 1 ts
public selectedOption:string;
view 1 html
<template>
<require from="../../Options/Options"></require>
<options selected-option.bind="optionTypes.selectedOption" view-model.ref="OptionTypes"></options>
</template>
view 2 that i am loading in view 1
ts
export class optionTypes extends Component {
#bindable selectedOption: string = '';
sOptions = ["1", "2", "3"];
async displayOption() {
if (this.selectedOption == "1") {
//gets the option selected
}
}
html
<select md-select value.bind="selectedOption">
<option value="">choose a option</option>
<option repeat.for="type of sOptions" value.bind="type">${type}</option>
</select>
<a md-button="flat: true;" md-waves="color: accent;" class="modal-action btn-custom-width " click.delegate="displayOption()">proceed</a>
the select html loads correctly in the view one.The only issue is that its not returning the value that the user selected in the selectOption.how do i get the value from view 2 in view 1?
i tried this option also but the selectedOption in view 1 is always undefined

Warning : select expects an Array value for its binding, but got String

the application i am working on includes 3 or 4 pages where the user is asked to enter some data in various fields (input, select). If the user wants to go back to a page, the previous data needs to be displayed (I get it from the store, using computed properties).
It works well on input type fields, however i get a warning with select type fields :
[Vue warn]: <select multiple v-model="tax"> expects an Array value for its binding, but got String
Here is an extract of the code in the template section of the selectTax.vue file :
<select v-model="tax" multiple="multiple">
<option value="tax1">Tax1</option>
<option value="tax2">Tax2</option>
<option value="tax3">Tax3</option>
Here is an extract of the code in the script section of the selectTax.vue file :
tax: {
get() {
return this.$store.getters.taxtype;
},
set(value) {
this.$store.commit("setTaxType", value[0]);
}
}
The problem is that the computed property tax is a string, not an array.
Is there any proper way to fix it ? Thanks for helping.
When using <select multiple the data model is not a string, but an array.
This is because the user can select more than one option.
You have 2 options:
update the data type for this.$store.getters.taxtype to be initialized with an array (empty most likely) and update
set(value) {
this.$store.commit("setTaxType", value);
}
or remote multiple from the select

Complex object in a dropdown using JSViews

I am working on project with JSViews, Observables and TypeScript.
I planned to handle several languages so I have an object that holds french and english version. A class with static methods that returns the collection of names and an array with all the static objects.
I wanted to display the objects in a dropdown with a converter to fetch the english name, I managed to fill the dropdown and react on change but I can't display the current item in the dropdown and I don't see what is missing.
Could you please help ? I made a javascript sample here :
https://jsfiddle.net/ClaudeVernier/v093uqg0/
var data = new dataModel();
for (var member in Harbors) {
if (typeof Harbors[member] == "object" && Harbors[member].name) {
data.harbors.push(Harbors[member]);
}
}
var myTmpl = $.templates("#harborTmpl");
myTmpl.link("#container", data);
$.observe(data, "*", myHandler);
Then, I'll need to figure how to change language on the click of a button, if you have idea on that... it would help :-)
Many thanks,
Claude
Take a look at Data-linked <select> elements - including the section <select> with converters.
Your code:
<select id="cboHarbor" data-link="{{getName:activeHarbor}}">
is incorrect. You need to data-link to activeHarbor. If activeHarbor was a string, you could data-link using:
<select id="cboHarbor" data-link="activeHarbor">
but since it is an object you need to have some kind of string-valued property for each harbor object, that you can then use for each option value. Then you will use converters to convert back and forth between the activeHarbor object and its string value property for the data-link binding behavior.
For example you can use the name in the current language as string value, but it is a bit strange to use a value that changes based on current language. But you need a getHarbor converter to convert back to get from the name to the harbor object. That would look like this:
<select id="cboHarbor" data-link="{getName:activeHarbor:getHarbor}">
{^{for harbors}}
<option data-link="{getName:}"></option>
{{/for}}
</select>
Alternatively you can use the index of the harbor in the array, like this:
<select id="cboHarbor" data-link="{getIndex:activeHarbor:getHarbor}">
{^{for harbors}}
<option value="{{:#index}}" data-link="{getName:}"></option>
{{/for}}
</select>
with converters as follows:
$.views.converters({
getIndex: function (harbor) {
return harbor.index;
},
getHarbor: function (index) {
return data.harbors[index];
},
getName: function (harbor) {
return harbor.name[data.languages[data.currentLanguage]];
}
});
If you want to be able to dynamically change language and have the harbors drop-down switch to the new language, then you must make your getName converter depend on the current language, like this:
$.views.converters.getName.depends = [data, "currentLanguage"];
Here is an updated version of your jsfiddle complete with a language drop-down to switch language.
UPDATE:
Concerning the depends for getName, a modified jsFiddle has this:
function getName(harbor) {
return harbor.name[data.languages[data.currentLanguage]];
}
$.views.converters({
getName: getName,
...
});
getName.depends = [data, "currentLanguage"];
So you can simply use a getName function as your converter function, and then in the context in which you have access to the data instance (in a done() if it needs to be async), you then assign the depends:
getName.depends = [data, "currentLanguage"];
No need to use $.views.converters.getName.depends

How can I make Meteor subscriptions dynamic?

I am looking to make my meteor subscriptions dynamic/reactive. Right now, I have a page that subscribes to a collection of templates based on a template ID that is assed to it:
Meteor.subscribe('templates', templateId)
On the same page, I have a dropdown list of template names and ID's:
<p><label>Select Template</label></p>
<select id="templateSelect" name="templateSelect">
<option disabled selected> Select Template </option>
{{#each orderTemplates}}
<option value="{{this._id}}">{{this.templateName}}</option>
{{/each}}
</select>
I want the subscription variable templateId to be equal to the option value of the template that I select. Anyone have any ideas? I'm really not sure where to begin with this one...
Thanks!
If you want a template subscription, you should follow this strategy:
Create a reactive variable scoped to your template.
Update (1) in your event handler.
Use a template subscription combined with a template autorun - this will ensure you have only one outstanding subscription and will automatically clean up the subscriptions when the template is destroyed.
Template.myTemplate.events({
'change #templateSelect': function (event, template) {
// extract the value/id from the selected option
var value = $(event.target).val();
// update the templateId - whis will cause the autorun to execute again
template.templateId.set(value);
}
});
Template.myTemplate.onCreated(function() {
var self = this;
// store the currently selected template id as a reactive variable
var templateId = new ReactiveVar;
// this will rerun whenever templateId changes
this.autorun(function() {
// Subscribe for the current templateId (only if one is selected). Note this
// will automatically clean up any previously subscribed data and it will
// also stop all subscriptions when this template is destroyed.
if (templateId.get())
self.subscribe('orderTemplateShow', templateId.get());
});
});
Recommended reading:
Scoped Reactivity
Template Subscriptions
Changing Templates and Subscriptions with Select dropdown
To get the id of the selected option use a jQuery selector to select by id then select .val() of that menu:
var templateId = $('select[id="templateSelect"]').val();
Meteor.subscribe('templates', templateId);

Can I bind data to data-win-options?

I use the control MicrosoftNSJS.Advertising.AdControl in the ItemTemplate of a ListView.
I would like to bind some datas to the following data-win-options properties : ApplicationId and AdUnitId
The source datas are correctly set and are visible in my item template, I can display them with an h2 + a classic data-win-bind on innerText property
Ads are displayed correctly if I put directly static IDs in html code but these IDs need to be loaded from a config file...
Is it possible ? Thanks
If it's not possible, can I modify directly the item template in the JS code before to be injected in the listview ?
Come to find out this is possible (I was trying to do something similar)
The syntax for the control properties must be prefixed with winControl.
Example (I'm setting the application id here but binding the html element's className and the ad control's adUnitId)
<div id="adItemTemplate" data-win-control="WinJS.Binding.Template">
<div data-win-bind="className:css; winControl.adUnitId: adUnitId"
data-win-control="MicrosoftNSJS.Advertising.AdControl"
data-win-options="{ applicationId: 'd25517cb-12d4-4699-8bdc-52040c712cab'}">
</div>
</div>
I finally found a way to perform this without real binding, by using the itemTemplateSelector function like this :
function itemTemplateSelector(itemPromise)
{
return itemPromise.then(function (item)
{
if (item.type == "ad")
{
var template = _$(".adTemplate").winControl.render(item, null);
// Access to the AdControl through the DOM
var adControl = template._value.childNodes[1].childNodes[1].winControl;
// Set options that are specified in the item
WinJS.UI.setOptions(adControl, { applicationId: item.AdAppId, adUnitId: item.AdUnitId });
return template;
}
else
{
return _$(".itemTemplate").winControl.render(item, null);
}
}
}
I had this problem in ratings:
<div data-win-control="WinJS.UI.Rating" data-win-options="{averageRating: 3.4, onchange: basics.changeRating}"></div>
I bind it via winControl:
<div data-win-control="WinJS.UI.Rating" data-win-bind="winControl.averageRating: myrating" data-win-options="{onchange: basics.changeRating}"></div>
It worked fine.
<div data-win-bind="this['data-list_item_index']:id WinJS.Binding.setAttribute" >