angular2 getting the whole object selected in a select box - javascript

In the past I was able to pass out the 'object' that was used for the select options. I'd like to capture that information off a regular select, but I cannot remember how.
So When you do an *ngFor in your select option, you specify a N of N's like this
<option *ngFor="let thing of things" value= {{thing.name}}>
{{thing.family}} - {{thing.name}}
</option>
I'm hoping I can get that 'whole' thing that was selected, by calling a function on change.
<select class="form-control input-sm "
(change)="changeThing($event)"
name="thing"
formControlName="thing" >
<option *ngFor="let thing of things" value= {{thing.name}}>
{{thing.family}} - {{thing.name}}
</option>
</select>
because I want to change some form options based on the 'family' of the thing, not the value that gets passed.
my function looks like this.
changeThing (thing) {
console.log('thing:', thing);
selectedFamily = ??;
}
The $event is probably the wrong thing to be looking at - I can get the value selected there, but I cannot find the whole "thing" that was selected.
Thanks for any help.

You can do that with the help of index
Template Side :
<select class="form-control input-sm "
[(ngModel)]="selectedValue"
(change)="changeThing($event.target.value)"
name="thing" >
<option *ngFor="let thing of things; let i = index;" [value]="i">
{{thing.family}} - {{thing.name}}
</option>
</select>
Component Side :
changeThing(index){
alert(this.things[index].family +' '+this.things[index].name );
console.log(this.things[index]);
}
WORKING DEMO

I hope it will help
<option *ngFor="let thing of things" value= {{thing}}>
{{thing.family}} - {{thing.name}}
</option>

You can use ngModel with ngModelChange
<select [(ngModel)] ="selectedType" (ngModelChange)="changeThing(selectedType)">
<option *ngFor="let thing of things" [ngValue]="thing ">
{{type.name}}
</option>
</select>

Related

vuejs - define v-model only when object exists

My select box is working fine when the variable item.ativo_retencao.id exists correctly.
<select name="ativo_retencao" v-model="item.ativo_retencao.id" class="form-control m-input">
<option v-for="ativo in ativos" v-bind:value="ativo.id">#{{ ativo.title }}</option>
</select>
So when it does not exists, I want to not define (or set null) the v-model property.
Is that possible?
you can use an ternary to do this:
<select name="ativo_retencao" :v-model="item.ativo_retencao.id ? item.ativo_retencao.id : ''" class="form-control m-input">
<option v-for="ativo in ativos" v-bind:value="ativo.id">#{{ ativo.title }}</option>
</select>
v-model is just syntactic sugar (code below applies just for select element):
v-model="item.ativo_retencao.id"
..is same as
:value="item.ativo_retencao.id" v-on:change="item.ativo_retencao.id = $event.target.value"
...so if you don't have a value you want to bind to, just don't render the select at all
<select v-if="item.ativo_retencao.id" name="ativo_retencao" :v-model="item.ativo_retencao.id" class="form-control m-input">
<option v-for="ativo in ativos" v-bind:value="ativo.id">#{{ ativo.title }}</option>
</select>

Angular 2 Html Select model not matching to option value

I have 2 arrays out of which 1 array values are bound to select dropdown values.
On clearing of another array, I want to render only one option.
Following is the code:
Component
#Component({
selector: 'my-app',
templateUrl : 'app/app.html'
})
export class AppComponent {
arrToClear = [1,2,3,4];
arrToBind = ["NONE", "SOME", "OTHER"];
modelToBind = 'NONE';
}
View
MODEL -> {{modelToBind}}
<button type='button'(click)="arrToClear.length = 0; modelToBind = 'NONE'">Clear Array </button>
<select class="form-control"
id="someId"
name="someName"
[ngModel]="modelToBind"
#someName="ngModel"
>
<ng-container *ngIf="arrToClear.length">
<option *ngFor="let data of arrToBind"
[ngValue]="data"> {{data}}
</option>
</ng-container>
<option value="NONE" *ngIf="!arrToClear.length">
Value
</option>
</select>
Problem is, when I clear "arrToClearArr" array, my selected value is empty. It should get bound to "A" because my model contains "A".
Additionally, I want only one-way binding hence I have used [ngModel].
What am I missing here? Any help will be appreciated.
Thanks.
Plunker Link
Expected behavior:
Change dropdown value
Click 'Clear array' button
Dropdown value should be "A", currently, it is ""
This is optional but personally I would not use the [ngModel] and try using Template-driven forms for this issue as I believe it would be clearer to just bind the variable directly.Just as you did with the for loop.
<select class="form-control" id="someId" formControlName="someName" name="someName">
<ng-container *ngIf="arrToClear.length">
<option *ngFor="let data of arrToBind" [value]="data"> {{data}}</option>
</ng-container>
<option [value]="modelToBind" *ngIf="!arrToClear.length">{{modelToBind}</option>
</select>
Alternatively could you not keep everything the same and just edit the last option.
<select class="form-control" id="someId" [ngModel]="modelToBind" #someName="ngModel" name="someName">
<ng-container *ngIf="arrToClear.length">
<option *ngFor="let data of arrToBind" [ngValue]="data"> {{data}}</option>
</ng-container>
<option [value]="modelToBind" *ngIf="!arrToClear.length">{{modelToBind}</option>
</select>

Conditionally showing options in a select with Angular

I am creating a template for showing Select fields in my app. However I have 4 different types of select field. value = id, value = name, value = static_id and value = static_name (it's complicated...).
I plan to migrate these to ngOptions if possible in the future, but for now I am attempting to have a single select template, that will handle all 4 types of field.
I currently use an ng-if to show the different 'static' code for a select, but this creates a lot of code that I want to reduce into this single template.
Here's some code:
// shows a basic select field where option value = id
<div ng-if="field.type=='select'" class="form-group">
<select-field></select-field>
</div>
// shows a basic select field where option value = name
<div ng-if="field.type=='select_name'" class="form-group">
<select-field></select-field>
</div>
// shows a basic select field where option value = static_id
<div ng-if="field.type=='select_static_id'" class="form-group">
<select-field></select-field>
</div>
// shows a basic select field where option value = static_name
<div ng-if="field.type=='select_static_name'" class="form-group">
<select-field></select-field>
</div>
Here, all the field attributes are identical, except for the generated options. Hence why I want to template this.
I am attempting to have this single template have another ng-if inside that will detect the field type, from the JSON it reads, and then change the options displayed accordingly, like this (2 of the 4 examples shown):
<select
name={{field.name}}
class="form-control form-field {{relationshipUrl}}"
id={{field.name}}
data-is-autofocus={{field.focus}}
data-selectreq={{field.rules.selectreq}}
data-showhide={{field.rules.showhide}}
>
<option value="" selected>Please select...</option>
<span ng-if="field.type=='select'">
<option
value={{option.id}}
ng-repeat="option in cache[field.relationshipURL] | orderBy:'name || firstName'"
ng-selected="formData[field.name] == option.id">
{{option.name || option.firstName}}
</option>
</span>
<span ng-if="field.type=='select_static_name'">
<option
value={{option.name}}
ng-repeat="option in cache[field.relationshipURL] | orderBy:'name'"
ng-selected="formData[field.name] == option.name">
{{option.name}}
</option>
</span>
</select>
Possibly horrible code to use a span within the select, but that's why I am coming to you good people. Currently this works in that it shows the correct options, however, it shows the options listed out twice, and I assume it will list them 4 times once all the option types are included. I hope that makes sense. Thanks in advance.
Well no sooner had I posted, the answer was blindingly obvious. Instead of the above approach by removing the span and putting the ng-if on the <option> instead fixed the issue and it works perfectly!
<select
name={{field.name}}
class="form-control form-field {{relationshipUrl}}"
id={{field.name}}
data-is-autofocus={{field.focus}}
data-selectreq={{field.rules.selectreq}}
data-showhide={{field.rules.showhide}}
>
<option value="" selected>Please select...</option>
<option ng-if="field.type=='select'"
value={{option.id}}
ng-repeat="option in cache[field.relationshipURL] | orderBy:'name || firstName'"
ng-selected="formData[field.name] == option.id">
{{option.name || option.firstName}}
</option>
<option ng-if="field.type=='select_name'"
value={{option.name}}
ng-repeat="option in cache[field.relationshipURL] | orderBy:'name'"
ng-selected="formData[field.name] == option.name" >
{{option.name}}
</option>
<option ng-if="field.type=='select_static_id'"
value={{option.id}}
ng-repeat="option in cache[field.relationshipURL] | orderBy:'name'"
ng-selected="formData[field.name] == option.id" >
{{option.name}}
</option>
<option ng-if="field.type=='select_static_name'"
value={{option.name}}
ng-repeat="option in cache[field.relationshipURL] | orderBy:'name'"
ng-selected="formData[field.name] == option.name">
{{option.name}}
</option>
</select>
Thank you anyway #charlietfl very quick response.
I'm a bit late for the answer, but I managed to make a working JSFIDDLE of what I hoped you tried to accomplish.
I factorized your code into a single select and added another select to show you how to display either only one, or all of them.
<div>
<select ng-model="selector">
<option value=""></option>
<option value="">Show everything</option>
<option ng-repeat="option in Options" value="{{option.type}}">{{option.type}}</option>
</select>
</div>
<div ng-repeat="option in Options" ng-show="$parent.selector == option.type || $parent.selector == ''">
{{option.type}}
<select>
<option ng-repeat="choice in option.choices" value="{{choice}}">{{choice}}</option>
</select>
</div>
And the data :
$scope.Options = [
{type:"id", choices:["0", "1", "2"]},
{type:"name", choices:["John", "Doe", "Smith"]},
{type:"static_id", choices:["3", "4", "5"]},
{type:"static_name", choices:["Static 1", "Static 2", "Static 3"]},
];

Detect changing of the select list value with AngularJS

I tried using ng-change on select but the problem is, I need to send ticket.id to the method but, ticket.name to model.
<select name="ticketAttendeeMapping"
ng-model="attendee.ticketTypeName"
class="form-control">
<option ng-repeat="ticket in inTransitionTickets | filter: greaterThan('countRemaining', 0)"
ng-value="ticket.name"
ng-click="onAttendeeTicketmapping(ticket.id, $parent.$index)">
{{ticket.name}}
</option>
</select>
I also tried doing this:
<select name="ticketAttendeeMapping"
ng-model="attendee.ticketTypeName" class="form-control"
ng-options="ticket.name as ticket.name for ticket in inTransitionTickets | filter: greaterThan('countRemaining', 0)"
ng-change="onAttendeeTicketmapping(ticket.id, $index)">
<option value="" disabled>Choose Your Ticket</option>
</select>
The easiest way is to just use the object in the model:
<select name="ticketAttendeeMapping" ng-model="attendee.ticket" class="form-control" ng-options="ticket.name for ticket in inTransitionTickets" ng-change="change(attendee.ticket.id)">
</select>
Then you can access the name by using $scope.attendee.ticket.name and you can access the id by using $scope.attendee.ticket.id
Plunkr
try to do this:
<select name="ticketAttendeeMapping" ng-model="attendee.ticketTypeName" class="form-control" ng-options="ticket.name as ticket for ticket in inTransitionTickets | filter: greaterThan('countRemaining', 0)" ng-change="onAttendeeTicketmapping(attendee.ticketTypeName, $index)">
<option value="" disabled>Choose Your Ticket</option>
</select>
now you will get ticket i.e."attendee.ticketTypeName" object in ur ng-change method. where u can get its "id"
I am not sure, If what I have done here is what was originally asked by OP.
We can't use ng-options here simply!!
because while we use "ng-options" it restricts our access to current selected Json element to the properties explicitly mentioned in ng-options, on the contrary ng-repeat gives you complete access to current Object.
<select name="ticketAttendeeMapping"
ng-model="SelectedTicketNameFromngModel"
class="form-control">
<option ng-repeat="ticket in ticketJson "
ng-value="ticket.name"
ng-click="alertMe(ticket.id)">
{{ticket.name}}
</option>
</select>
$scope.SelectedTicketNameFromngModel = '';
$scope.selectTicketIdFromMethod = '';
$scope.ticketJson = [{'name':'tick1','id':'t1'},{'name':'tick2','id':'t2'},{'name':'tick3','id':'t3'}];
$scope.alertMe = function(tId){
$scope.selectTicketIdFromMethod = tId;
}
http://jsfiddle.net/HB7LU/16124/

How to keep the selected value after selecting from options?

I'm quite new at AngularJS programming, just a few weeks with it and I would like to understand why, in the select box I use, when reloading the page or switching between pages and returning to this one, the option selected does not stay as the main option to be shown, and the option <option value="" selected>No assignat</option> is the one that always stays there?
<select ng-model="selected" ng-options="poblacio.title for poblacio in poblacions" ng-change="canviarPoblacio(selected)">
<option value="" selected>No assignat</option>
</select>
-CONTROLLER
.controller('ConfigCtrl', function($scope, noms, fPoblacions){
$scope.poblacions = fPoblacions.getPoblacionsConfig();
$scope.selected = localStorage.getItem('nomPobleConfig');
$scope.canviarPoblacio = function(objPobla){
localStorage.setItem('nomPobleConfig', objPobla.title);
localStorage.setItem('idPobleConfig', objPobla.id);
window.location.reload();
}
})
$scope.poblacions receives a list of names from a factory and the name that the user selects is storaged at the localstorage and would have to remain selected in the Select box, I hope you can help me :)
Excuse me if my english's not good at all, thanks for your future answers and I hope I find in them what I have not by searching and researching here in stackoverflow and everywhere..
-EDITED
I would like to add that, when I run it to see how it works, that's what appears in the Chrome console:
<select class="selectBox ng-pristine ng-untouched ng-valid" ng-model="selected" ng-options="poblacio.title for poblacio in poblacions" ng-change="canviarPoblacio(selected)">
<option value="" selected="selected">No assignat</option>
<option value="object:9" label="name1">name1</option>
<option value="object:10" label="name2">name2</option>
<option value="object:11" label="name3">name3</option>
<option value="object:12" label="name4">name4</option>
<option value="object:13" label="name5">name5</option>
<option value="object:14" label="name6">name6</option>
<option value="object:15" label="name7">name7</option>
<option value="object:16" label="name8">name8</option>
<option value="object:17" label="name9">name9</option>
<option value="object:18" label="name10">name10</option>
<option value="object:19" label="name11">name11</option>
<option value="object:20" label="name11">name11</option>
<option value="object:21" label="name12">nam12</option>
<option value="object:22" label="name13">name13</option>
<option value="object:23" label="name14">name14</option>
<option value="object:24" label="name15">name15</option>
</select>
I mean, the values assigned automatically are object:xx, and I suppose that it would be better to be the id's of every name, which in the factory are 1,2,3,4,5... respectively, same ID as the nameXX number.. if this can be solved too, it would be good :)
Since you are using ng-model='selected' You have to initialize $scope.selected like:
$scope.selected = localStorage.getItem('nomPobleConfig');
When you set $scope.selected, you are only setting it to the "title", not the actual selected object.
localStorage.setItem('nomPobleConfig', objPobla.title);
You'll need to set the full object into localStorage like this:
localStorage.setItem('nomPobleConfig', objPobla);

Categories

Resources