Is it possible in Angular to display a value in an option but return an array to the ngModelChange? - html

I am trying to organize a drop down list that will display a single value to the user but will also pass back an array object upon changing the selection.
Currently I have an array called classificationresult that has 3 elements CLASSIFICATION_NAME, GROUP_ID, GROUP_NAME.
When a user selects a particular CLASSIFICATION_NAME I want to pass back the entire array result containing all 3 elements listed above.
Currently the code below works for everything EXCEPT showing the CLASSIFICATION_NAME in the drop-down box upon loading. It shows the list once you click, but it starts with a blank until it is clicked. Any way to fix this? I believe the display element is tied to [ngValue] but that is also what I am using to pass back the entire array versus just the one.
Any help would be greatly appreciated.
<p>Select Classification*</p>
<select [(ngModel)]="selectedClassification (ngModelChange)="changedClassification($event)">
<option *ngFor="let classificationresult of classificationresults" [ngValue]="classificationresult" >{{ classificationresult.CLASSIFICATION_NAME }}</option>
</select>
Summary -- I want my drop down list to always have a value shown to the user (value being the Classification Name) but when one is selected I want the entire array to pass to the changedClassification function. Also sometimes after a user selects from other drops down on this page they will also go blank, but if they are selected a second time they will populate.

If everything is working as you are expecting except the initial value being displayed, I wonder if you need a [compareWith] function. I don't know what your classificationresult model looks like, but if I had to take a guess, putting a [compareWith] function on your <select> element would fix the issue.
Here is an article explaining it a little more.
I made this Stackblitz as an example with using the [compareWith] function. In my demo I am using ReactiveForms, but the compareWith should still be the same.
For your code, it may look something like:
<p>Select Classification*</p>
<!-- add this [compareWith] -->
<select [compareWith]="myCompareFunc" [(ngModel)]="selectedClassification" (ngModelChange)="changedClassification($event)">
<option *ngFor="let classificationresult of classificationresults" [ngValue]="classificationresult" >{{ classificationresult.CLASSIFICATION_NAME }}</option>
</select>
In your .ts file:
export class YourComponent {
// all your component code..
/* compare function, change the logic to fit your needs */
myCompareFunc (classificationRes1: any, classificationRes2: any): boolean {
return classificationRes1 && classificationRes2
? classificationRes1.CLASSIFICATION_NAME === classificationRes2.CLASSIFICATION_NAME
: classificationRes1 === classificationRes2
}
}
If that doesn't fix your issue, you may need to post more of your .ts code and data models.

Related

Options for select list from model variables and for loop

I have a model containing users, I want to make a dropdown list with these users' UserName as display and their IDs as values, but it is not working. Whichever user I choose from the dropdown list, when I proceed, the chosen value seems to be the Id of the current user, no matter which I choose.
When replacing this select with an input box the other part which uses the user Id works just fine. It seems as all value attributes for the options become the current user's Id instead of the chosen ones.
I've tried injecting javascript, I've tried changing the value=Item.Id for other things, nothing so far has worked. The dropdown list does become populated, but the value attribute seems to be off somehow.
<select asp-for="Input.UserID" onfocus="this.select()">
#foreach (var item in Model.Users)
{
<option value=Item.Id>#Html.DisplayFor(modelItem => item.UserName)</option>
}
</select>
The webpage always throws an error stating that the chosen User ID is the one of the currently logged in user.
You aren't setting the value="" attribute of the <option> element correctly. You also don't need to use DisplayFor for a string value.
<select asp-for="Input.UserID">
#foreach( var item in this.Model.Users ) {
<option value="#(item.Id)">#(item.UserName)</option>
}
</select>
That said, consider using this instead:
<select asp-for="Input.UserID" asp-items="#this.Model.UsersOptions"></select>
You'll need to add a List<SelectListItem> UsersOptions to your ViewModel for this to work.

Unable to Correctly Populate Select with ngFor

I am attempting to create a select in my Angular app based on a classificationsList array from the component. As of now, the view initiates with the first value already "selected", but validation marks it as an invalid response.
If I select the dropdown and choose the other option, it returns valid.
(before selection)
(after selecting)
But when I go back to select "Class 1" it registers as invalid again.
What I'm expecting this to do is have the default, empty option (like below), that disappears once a real option is selected. The difference between these two lists is that the classificationsList is dynamic, whereas the the department list is static.
In fact, I took the html block from the department list and just added the *ngFor piece. Can someone tell me what I'm doing incorrectly, here? The issue isn't strictly with the validation, however. The bigger issue is the fact that it defaults to the first value in the array instead of an empty value like Department. When I put an empty string into the first item of the array from the component side, it selects the empty value like it selects "Class 1" as you've seen.
The validation actually performs fine here, as the empty string is invalid, and the rest of the array items are valid. In this scenario, though, there is an empty string still available in the option.
<div><label for="titleClass">Title Classification</label></div>
<select name="titleClass" id="titleClass" ngModel required>
<option *ngFor="let class of classificationsList">{{class}}</option>
</select>
</div>
I got it! The functionality I was looking for required me to set a default value (unattached to the array). For this one, I set the default as null like below.
<div class="formBoxRows">
<div><label for="titleClass">Title Classification</label></div>
<select name="titleClass" id="titleClass" ngModel required>
<option *ngFor="let class of classificationsList" [value]=null>{{class}}</option>
</select>
</div>

angularjs setting different options on multiple dropdowns

I hope there's a way to achieve this.
I am creating dropdowns using ng-repeat; the number of dropdowns created depends on the data I retrieve from the database.
Depending on the data,I'd like to set an initial option value for each dropdown.
Consider the following code:
<span class="finds" ng-model="cond" ng-repeat="condin list">
<select ng-model="selected_item" ng-options="condition.name for condition in conditionTypes"></select>
<input ng-model="cond.name"/>
</span>
I can change the values of the dropdown by changing the selected_item value but this changes the value of all dropdowns (because the variable is binded).
So is it possible for me to change the value of each dropdown independently without affecting other dropdowns(without creating multiple variables as well)?
Thank you
If you want your right drop-down to be filled with appropriate data according to the value in your first select box you should be doing something like this.
Suppose you have two drop-down list like;
<select ng-model="first" class="form-control" ng-change="secondcall()">
<option ng-repeat = "firstdata in firstdatas" value="{{firstdata}}">{{firstdata}}</option>
</select>
<select ng-model="second" class="form-control">
<option ng-repeat = "seconddata in seconddatas" value="{{seconddata}}">{{seconddata}}</option>
</select>
In your controller;
$scope.secondcall = function () {
var value = $scope.first;
//Make an API call to fetch details with the select value and in the success do this
$scope.seconddatas = data from the api;
};
There's only one ng-repeat and that is used to create a set of dropdowns.
I need to retrieve the data from the database and depending on the data I can then define how many dropdowns I will need.
the ng-repeat does that. if, after processing the data I need 2 dropdowns then I'll create two pairs inside the loop
dropdown1 dropdwon1.0 {1.0 should load list depending on the option chosen in 1
dropdown2 dropdown2.0 {2.0 should load list depending on the option chosen in 2

retrieving object properties from angularjs factory

I am completely stumped on this one. Everything's working fine (or fine enough for now) and all I need is to get the data back out of the factory in a non-json format. I've got a semi-working plunker with all the details.
Basically, the first page (under the Ctrl controller) is where a user can check a bunch of boxes. There's also an ng-switch between sets of options (the real things are much, much larger lists than these), so the checkboxFactory maintains the user's choices. When the user goes to the next page (or "next page" in the plunker because faking it), they can see what they chose. Those choices will then get wrapped up in a json post back to the server. I need to show the user-friendly name, but also have the id# of the choice, for the server.
If I put value="{{item.name}}" in the original checkbox ng-repeat, everything is fine. Except for the fact that then I have a factory of names, and not the server-required ids. Doing a second array in the factory (one for selected names, one for the corresponding selected ids) seems like overkill, when theoretically I could just add each selection as an object, and extract the properties as needed on the second page.
In reality, it's not working. Here's what I get if I echo the factory, after selections are made:
[ "{\"id\":1,\"name\":\"Firstplace\"}", "{\"id\":2,\"name\":\"Second place\"}" ]
...and I'm not sure, but those backslashes seem to be turning every selection into strings, because there are quotes just inside the square brackets. I've tried editing line 54 in the script, but I get errors. It doesn't like this:
if (checked && index == -1) {
if (setup) elem.prop('checked', false);
else scope.list.push({
id:"scope.value.id",
name:"scope.value.name"
});
On the html side, it doesn't like any of the variations I've tried in the ng-repeat, either. It seems like the source of all nightmares is that pushing is creating deformed json. I've tried all of these the second page/output:
{{item}}
{{item.name}}
{{item.item.name}}
The only one that works is {{item}} and unsurprisingly it's pretty ugly. Has anyone run into this before, and have any hints on how to fix this? Many thanks in advance.
using # will turn your object into a string, you should just use a reference to your item object instead and use =.
Change {{item}} to just item as a reference:
<input type="checkbox" name="group1" value="item" ng-model="isChecked" checkbox-list='checkedCity' />
In directive use =:
scope: {
list: '=checkboxList',
value: '='
},
see updated plunker

Angularjs - select/options - set default selection after applying filter

Please take a look at this plunkr.
I have a couple of select lists that are filtered based on some simple conditions. There is a list (of Plants) that is dynamically constructed by clicking on the "Add" button. When each row is added, I would like the selects to automatically select the first item in the list. Please bear in mind that there are filters and the items change based on the select list on the top of the form (SalesOrg).
Preferably, I would like to do this without using DOM in the controller.
UPDATE: Have a look at this simpler plunk. Select "Texas" as the state. The city dropdown has been accordingly filtered. The initial selection does not work because the original dropdown variable (DropDownData.Cities) is no longer the source of the select - it has been filtered.
Just useng-init like:
<select class="form-control" id="selSalesOrg" ng-model="SelData.SalesOrg"
data-ng-options="salesOrg.id as salesOrg.Description for salesOrg in DropDownData.SalesOrgs"
ng-init="SelData.SalesOrg = DropDownData.SalesOrgs[0].id">
</select>
The fixed PLunker
The second way is instead ng-init directive add to your controller something like:
$scope.SelData.SalesOrg = DropDownData.SalesOrgs[0].id;
Comment**
Since you use filter actually we can't take first element but first in list after filtering