So I have an odd behavior that I want to implement on my dropdown. I have two scenarios and both will have different default selected values.
Scenario 1: If user role is admin, then dropdown will not be disabled and 'Select Location' placeholder will show up as selected default.
Scenario 2: if user role is clerk, then dropdown will be disabled and the selected value will be a specific location from the dropdown selection.
While I got the role permission and disabled/enabled thing setup, I'm not sure how to dynamically change the selected value of the dropdown. This is inside reactive forms form group, so not sure I can use ngModel or can I?
Here's my dropdown:
<select [ngModel]="null" formControlName="location" required >
<option value="null" disabled>{{'SelectLocation' | translate}}</option>
<option selected *ngFor="let store of location" [ngValue]="store._storeKey">{{ store._storeName }}</option>
</select>
Here's the check I have that disables/enables the dropdown:
checkUserPermissions() {
if (this.userPermissions._userPrivilegeKey === 100) {
//TODO: Default to store2 of list for example
this.transactionForm.controls['location'].value = stores._store; // This is right?
this.transactionForm.controls['location'].disable();
} else if (this.userPermissions._userPrivilegeKey === 200) {
//TODO: Default to select location placeholder (currently working)
this.transactionForm.controls['location'].enable();
}
}
You should use the patchValue function instead of directly assigning the value when dealing with forms
this.transactionForm.controls['location'].patchValue(stores._store)
Related
I have a form in Angular 9, let's say it's for a language school. I want that the user can choose which language to study from a dropdown AND to add multiple languages by using "Add Language" button which adds another dropdown. The trick is that in the new dropdown, already selected languages shouldn't be available in the dropdown options. I followed the first answer to this question and all good:
How to remove the previously selected option from a drop-down menu in a table?
So, I have a array containing all available language names:
languageNames = [
{'name': "English"}, {'name': "Russian"}, {'name':"Spanish"}, {'name':"Czech"}, {'name':"Croatian"},
{'name':"Italian"}, {'name':"French"}, {'name':"German"}
];
I'm also watching what the user selected with:
#ViewChildren("selectLang") langSelects: QueryList<HTMLSelectElement>;
selectedLangs = new Set<string>();
Then I let the user choose a language from a dropdown:
<mat-select formControlName="name" (selectionChange)="selected()" #selectLang>
<ng-container *ngFor="let language of languageNames">
<mat-option *ngIf="selectLang.value === language.name || !isSelected(language.name)" [value]="language.name">
{{language.name}}
</mat-option>
</ng-container>
</mat-select>
on selection change I clear my selectedLangs set, the grab all the values from my form and add them back:
selected() {
this.selectedLangs.clear();
for (let c of this.languageForm.controls) {
const selectedVal = c.get('name').value;
if (selectedVal && selectedVal !== "undefined") this.selectedLangs.add(selectedVal);
}
}
and this is how I check should I show my option or not:
isSelected(lang: string) {
return this.selectedLangs.has(lang);
}
It works perfectly.
But, let's say a user in the future want's to edit his or her submission. When I fetch my data I add the selected languages to selectedLangs string Set using a forEach loop on my incoming data and selectedLangs.add(lang). The reason I want them in that string set is if a user adds a new dropdown for adding a new language, their previous selected languages shouldn't be available in the dropdown options. But here's the problem with this logic - in my edit form I only have empty dropdowns for each language selected when the user previously submitted the form because they are in the selectedLangs set.
These dropdowns should be populated with languages selected when submitting the form but they are empty
How to show previously selected values when I edit my form so the user can see which languages he selected but with the functionality that works just great when creating a form?
with JS you can set the selected value with .value
selectElement.value = "selected value"; The value needs to be the same as in the option value.
I am working on an AngularJS 1.0 application and facing an issue with Angular Select.
Just Copying a dummy code:
<select ng-model ="data.state" ng-options="data.states">
Select
Here, it's listing states of a country and passing a default data as ng-model.
I need to show a text "Select" if default is not matching with the data source.
But it's not working as expected and it's showing an extra empty space instead of select.
Thanks
"I need to show a text "Select" if default is not matching with the data source." In this case your data.state may be empty (ie "") case. You may be expecting some logic like this:
<label>States : </label>
<select ng-model ="data.state" ng-options="data for data in data.states" >
<option value="" selected hidden >SELECT</option>
<!--Removes the Empty space and shows "SELECT" as pre-populated by default in the drop-down. -->
</select>
<br>Selected State : {{data.state}}
Empty space appears as a placeholder offered by Angular to hold text like "Select an option" or "Choose a best answer". You can override this using the <option value="" selected hidden >Select</option> which won't appear in the selected drop down options list as it is hidden.
If you wish to have the select appear as an option for user to choose in order if the field can be remained empty and is not mandatory you can use the following code instead:
<option value="" selected >SELECT</option>
In controller expecting the data as:
// $scope.data.state = something that is returned from some API response
$scope.data = {
states: [
"Kerala",
"Karnataka",
"Andhra",
"Haryana"
]
}
Checkout the JS Fiddle here for working sample.
<select ng-model ="data.state" ng-options="data.states">
make use of track by in ng-repeat. track by $index or id if any
I have two dropdown in my example with reset state (select bank select state).only first dropdown have data .When I changed first dropdown value then i fetch state data and show in dropdown . if i select YES BANK it show me select state .Now if I select any state example Delhi.then do something.But Now If I change again bank instead of yes bank example Axis bank state dropdown show Delhi why ? it show be reset and show select state ?
how to reset second dropdown (when first dropdown is change).here is my code
https://codesandbox.io/s/7wlwx2volq
Second dropdown always show select state with new data of bank,when user change bank name
onChangeDropdown = e => {
console.log(e.target.value);
this.props.callbackFn(e.target.value);
};
please explain
One possible solution is: Instead of using the selected property on options, use controlled component means use the value property of select field. Whenever any change happen to bank list, reset the value of state select filed value. Also define the value='' with default option.
Like this:
<select value={this.props.value} onChange={this.onChangeDropdown}>
<option value='' disabled>
{this.props.defaultOption}
</option>
{makeDropDown()}
</select>;
Pass value from parent component, like this:
<DropDown
value={this.state.bankName}
data={this.state.bankData}
defaultOption="select Bank"
callbackFn={this.callStateService}
/>
<DropDown
value={this.state.stateName}
data={this.state.stateData}
defaultOption="select State"
callbackFn={this.callDistrictService}
/>
Define onChange function for state select field change:
callDistrictService = value => {
this.setState({ stateName: value });
}
Working Sandbox.
I am trying to make that after new value is selected, I call eventChange() function and restore selected value to default. But what happens: ngModel value updates, but selected value stays the same. How should I do that selected value and ngModel value would be the same?
HTML file
<select [(ngModel)]="selectedValue"
(change)="eventChange()"
>
<option [disabled]="true"
[ngValue]="-1">
Choose an option
</option>
<option *ngFor="let item of myList index as i"
[ngValue]="i"
>
{{item.name}}
</option>
</select>
Function from Component file
selectedValue = -1; //works //Option in select is changed
eventChange(){
this.selectedValue= -1; //don't work
//Function is called,
//Value changes
//But selected Option in Select doesn't change
}
Comment:
On running web page(refresh) first value of select is set properly, if in component file I set variable selectedValue to other index the other value is selected, but it works only on run, but not in function)
Also I found this question Angularjs: select not updating when ng-model is updated
But here is an answer to AngularJS for using ng-options, instead of ng-repeat, in angular 4 I found only *ngFor...
Update:
Clarification just in case: function is being called, but I want change selected option through javascript. I try this by changing ngModel value, but even when ngModel value is cahnged, selected option doesn't change.
Use ngModelChange and you don't need [ngValue]
<select [(ngModel)]="selectedValue"
(ngModelChange)="eventChange()"
I have a simple HTML select with options. What I do is - set an option of that control as selected just after the page is loaded. My question is - how can I do that so the users won't see the first option of the select and will see the select with the value from the DB set. Here's the example:
<select id="simpleSelect">
<option value = "1">One</option>
<option value = "2">Two</option>
<option value = "3">Three</option>
</select>
Setting the value as follows:
$("#simpleSElect").val(2);
Now the users will see the select with selected option "One" and it will flash changing the option to "Two" once the jQuery code is executed. This flashing does not look good and I'm curious if there's a way to prevent this flashing and show the users the select with directly "Two" selected.
Thanks.