Show default selection in Select dropdown - Angular - javascript

Here is my code:
<select label="people" id="ppl" [(ngModel)]="Selectedppl" (ngModelChange)="onPplSelection($event.target.value)">
<option>select people</option>
<option *ngFor="let x of peopleList" [ngValue]="x">
{{x.name}}
</option>
Since people list is an object with name, address, contact. I want to send object as params to ngModelChange with ngValue.
But, once I selected a particular people and saved.I want the dropdown to be changed as the selected people name. Basically, I want to
show the default selected option in dropdown once saved.
Am not using Reactiveforms.

You can have the reference of element and pass its value to function.
<select label="people" id="ppl" #ppl="ngModel"
[(ngModel)]="Selectedppl"
[compareWith]="compareFn"
(ngModelChange)="onPplSelection(ppl.value)">
<option>select people</option>
<option *ngFor="let x of peopleList" [ngValue]="x">
{{x.name}}
</option>
</select>
ts
If you have complex object then you must ue compareFn which help Angular to compare the object to set the default value.
compareFn(a, b) {
if (!a || !b) {
return false;
} else {
return a.name === b.name;
}
}
Working copy is here - https://stackblitz.com/edit/hello-angular-6-2z9f3b

Related

Angular5 select model

I have a Angular5 <select> bound to array of customers. See below:
<select class="form-control" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
<option *ngFor="let x of customers" [ngValue]="x.id">{{x.name}}</option>
</select>
In setCustomer function I get an customer's id as 'event'.
Property record.customer_id is type of number, not object. Is there any way how to get a whole customer entity in setCustomer method and also preserve binding to record.customer_id ?
I found on Angular docu a way [compareWith] so I tried:
<select class="form-control" [compareWith]="compareCustomer" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
<option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>
and
compareCustomer(c1: customer, c2: number) : boolean {
if (c1 == null || c1 == undefined) {
return false;
}
if (c1.id == c2) {
return true;
}
return false;
}
Does not work. When I select any option, setCustomer is executed, record.customer_id gets selected id. However, after select loses focus, selected option is reset to blank.
There is a workaround (iteration in customers array and manual match by id) that I want to avoid:
setCustomer(event) {
this.record.customer_id = Number.parseInt(event);
customers.forEach(c => {
if (c.id === this.record.customer_id) {
// some logic with selected customer
}
});
}
Any advice?
Thanks!
Instead of bind customer_id, bind the whole object:
<select class="form-control" [ngModel]="record" (ngModelChange)="setCustomer($event)" name="customer_id">
<option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>

content select option based on previous select option angularjs

i want to create 2 select option which the content of the other one selected option based to previous option. here is my html
<div class="col-sm-2">
<select class="form-control" ng-model="y">
<option value="1">a</option>
<option value="2">b</option>
</select>
</div>
<div class="col-sm-2">
<select class="form-control" ng-model="z">
<option ng-repeat = "x in list" value="{{x.idproduct}}">{{x.descproduct}}</option>
</select>
</div>
but there is error, the other select option wont showing the option like in this picture
here is my js file
if ($scope.y === 1) {
$scope.list = [
{idproduct:"13", descproduct:"cc"},
{idproduct:"14", descproduct:"dd"}
];
}
if ($scope.y === 2) {
$scope.list = [
{idproduct:"15", descproduct:"ee"}
];
}
You need to bind the change event so that your list gets updated at the time that your value is updated. Plus your === can cause an issue. With === your string value is being compared to integers 1 and 2.
Here is a plunker: ng-change for change in dropdown
<select class="form-control" ng-model="y" ng-change="updateList()">
<option value="1">a</option>
<option value="2">b</option>
</select>
$scope.updateList()={
if ($scope.y == 1) {
$scope.list = [
{idproduct:"13", descproduct:"cc"},
{idproduct:"14", descproduct:"dd"}
];
}
if ($scope.y == 2) {
$scope.list = [
{idproduct:"15", descproduct:"ee"}
];
}
}
The value of your option is String value="2"
And you're comparing it to an Integer if ($scope.y === 2)
You should compare it like if ($scope.y === '2') or if (parseInt($scope.y) === 2)
Create a function and put your Js code in that function and call function on ng-change of the first dropdown. Here you if condition executes once during app initialization. So by triggering ng-change we can call function and update the lists based on the selection.

Filter Two Dropdowns Based on One Another the Angular Way

I've got two dropdowns. The allowable options in those dropdowns should be filtered based on what's in the other dropdown. Here's the first dropdown:
<select ng-model="filter.levelPregenerate">
<option value="">All</option>
<option value="assox">Associate's</option>
<option value="bachx">Bachelor's</option>
<option value="mastx">Master's</option>
<option value="doctx">Doctorate</option>
<option value="nondx">Non-Degree</option>
<option value="bridx">Bridge</option>
</select>
And the second dropdown is an ng-repeat, as follows:
<select ng-model="filter.degreeTypePregenerate">
<option value="">All</option>
<option ng-repeat="type in degreeType | orderBy:'toString()'">{{type}}</option>
</select>
And here's the array being repeated above:
$scope.degreeType = ['BA', 'BS', 'MA', 'MBA',
'MDIV', 'MED', 'MFA', 'MPH',
'MS',' DNP', 'EDD', 'PHD',
'EDSPL', 'GRDCERT'];
The options in the first and second dropdown should be filtered based on each other. Here's the mapping between the two (how the filter should work):
assox: '';
bachx: 'BA, BS';
mastx: 'MA, MBA, MDIV, MED, MFA, MPH, MS';
doctx: 'DNP, EDD, PHD';
nondx: 'EDSPL, GRDCERT';
bridx: ''
So, if 'BA' is selected in the second dropdown, 'bachx' should be the only option available in the first dropdown. Conversely, if 'doctx' is selected in the first dropdown, 'DNP', 'EDD', and 'PHD' should be the only select-able options in the second dropdown.
Here's a Codepen with the full code: http://codepen.io/trueScript/pen/LVZKEo
I don't think I can simply apply a basic '| filter:foo' to the second dropdown, because it wouldn't know how to filter it. What is the Angular way to do this?
You could set up a custom filter and return the values that should be displayed. Two ways of doing it:
Option 1 - If/else
angular.module('programApp', [
'programApp.controllers',
'programApp.filters'
]);
angular.module('programApp.filters', [])
.filter('dropdownFilter', function() {
return function(input, degreeTypePregenerate) {
if (degreeTypePregenerate === 'assox') {
return [];
} else if (degreeTypePregenerate === 'bachx') {
return ['BA', 'BS'];
}
// and so on..
}
});
Option 2 - An object (cleaner in my opinion)
angular.module('programApp.filters', [])
.filter('dropdownFilter', function() {
return function(input, degreeTypePregenerate) {
var degreeType = {
'assox': [],
'bachx': ['BA', 'BS']
};
return degreeType[degreeTypePregenerate];
}
});
Finally, apply the filter to your ng-repeat, passing in the variable you want to filter by:
<option ng-repeat="type in degreeType | orderBy:'toString()' | dropdownFilter:filter.levelPregenerate">{{type}}</option>
Working codepen: Codepen

angular best practice for select show options when other select changes

i'm trying to build a select box that trigger show on options of other select in angular way.
the json that i use build select boxs is
[
{"item_id":1,"item":"rubber","type":"x","facility":"school a"},
{"item_id":2,"item":"pen","type":"x","facility":"school b"},
{"item_id":3,"item":"book","type":"y","facility":"school b"},
]
what i need is 3 select boxes, first one shows all unique type. in above json that would be 'x,y'.
when user select one of them, then it should show all unqiue facility values in other selectbox that has same type as selected.
--if user selected x, then it would show school a and school b
when user select facility, a 3rd selectbox show all uiqiue item as label, and item_id as value where facility = selected facility
<select ng-model="selected.type">
<!-- need to show unique types here -->
</select>
<select ng-model="selected.facility">
<option ng-repeat="s in json" ng-if='selected.type == s.type'>{{s.item}}</option>
</select>
<select ng-model="selected.item">
<option ng-repeat="s in json" ng-if='selected.facility == s.facility'>{{s.item}}</option>
</select>
Current solution
currently what i'm doing is that i wrote a filter
.filter('unique', function() {
return function (arr, field) {
var r = [],final=[];
for(i in arr){
if(r.indexOf(arr[i][field]) == -1){
r.push(arr[i][field]);
final.push(arr[i]);
}
}
return final;
};
})
and doing
<select class="form-control" ng-model="nrequest.facility">
<option ng-repeat="s in facility_services |unique:'facility'" value="{{s.facility}}">{{s.facility}}</option>
</select>
<select class="form-control" ng-model="nrequest.item">
<option ng-repeat="s in facility_services" ng-if='s.facility == nrequest.facility'>{{s.item}}</option>
</select>
it works yet i'm not sure if this is correct way to do it angular way, since i'm still learning this new toy i was hoping for some directions on how to achieve this using ngoptions, or other angularjs best practice

Obtain the number of the item in an options menu?

I'm using .val() in jQuery to retain the value of an options menu onChange.
How would I retain the number (as in as it is ordered) of the item in the drop down using jQuery?
<select>
<option> //option 1
<option> //option 2
</select>
Here is what I have set up now:
<select id="start_month" onChange="getMonthDay()">
<option>Jan</option>
<option>Feb</option>
<option>March</option>
<option>April</option>
<select>
Using,
function getMonthDay()
{
$('#start_month').val()
}
I can get whatever value is selected, but my question is how do I get the Number down of this value in the markup? For March, I would want 3.. and so on
Can you reformulate your question better? I'm still lost in what do you want.
But, nevertheless here is how <select> works in jQuery
<select id="selection">
<option value="val_1">value 1</option>
<option value="val_2">value 2</option>
</select>
$("#selection").val() will give you val_1 or val_2 depending on witch item is currently selected.
If you want to go through all options and check the selected on, you can use
$("#selection option:selected").val();
or itenerate through all <option>'s
$("#selection option").each(function() {
if( $(this).is(":selected") ) {
var v = $(this).val();
}
});
If you want to retain all options you can easily clone them or assign them as data, if you want to keep those values throughout the pages, use Local Database or Cookies to persist the data.
To answer your question after your update:
First: Why don't you have:
<select id="start_month" onChange="getMonthDay()">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">March</option>
<option value="4">April</option>
<select>
And use the value of the selected item?
Second: Just use what I wrote above and itenerate through the options
$("#start_month option").each(function(index, element) {
if( $(this).is(":selected") ) {
// get index position, remember to add 1 as arrays start at 0
var n = index;
// break each
return false;
}
});
You'd get a list of the <option> elements, find the selected one, and use index:
var $opts = $('#start_month option');
var zero_based_index = $opts.index($opts.filter(':selected'));
Demo: http://jsfiddle.net/ambiguous/HyukW/
Just add 1 if you want a one-based index.
I made something like this,with zero based key ;
<select id='deneme'>
<option>Val1</option>
<option>Val2</option>
<option>Val3</option>
<option>Val4</option>
</select>
$('#deneme').change(function(){
$.each( $('#deneme').children('option'),function(key,value){
if($(this).is(':selected'))
alert(key)
})
})
u can check from here http://jsfiddle.net/8JZCw/
No need for any iteration here, let jQuery do that for you, just get the selected index and increment...
$('#start_month option:selected').index() + 1

Categories

Resources