Remove selected option from drop down in Angular - javascript

I have a button which adds more select drop downs when clicked. So I would like to remove the already selected options in these select boxes for preventing duplication.
The following code is used for the select drop down:
<select class="select form-control"
formControlName="environment_id" (change)="onEnvChange($event.target.value)">
<option selected="selected" disabled value="">Select Environment
</option>
<ng-container *ngFor="let environment of environments">
<option *ngIf="!selectedEnvironments.includes(environment.environment_id)"
[value]="environment.environment_id">
{{environment.environment_id}}</option>
</ng-container>
</select>
and in the component I ave the following function for change
public onEnvChange(selectedEnvironment)
{
this.selectedEnvironments.push(selectedEnvironment);
}
Now when I select an option, that option itself gets removed from the dropdown. For example if I have options like option1,option2,option3 etc, when I select option1, option1 is getting removed from the dropdown. How to fix this and remove the option only for the next select dropdown ?

You can try create two objects of environments and listen selection with valueChanges from formControl. After you get the selected environmentid and filter the other object without this id
Example
ngOnInit(){
this.createForm();
this.getEnvironments();
this.environmentChanges()
}
createForm(){
this.form = this.fb.group({
'environment_id_1': [''],
'environment_id_2' : ['']
})}
getEnvironments(){
const environments = [
{ 'environment_id': 1, 'environment': 'A' },
{ 'environment_id': 2, 'environment': 'B' },
{ 'environment_id': 3, 'environment': 'C' },
{ 'environment_id': 4, 'environment': 'D' }];
this.environments1 = environments;
this.environments2 = environments;}
environmentChanges(){
this.form.controls['environment_id_1'].valueChanges
.subscribe((environment_id)=>{
this.environments2 = this.environments1.filter((env)=> env.environment_id != environment_id)
})}
<form [formGroup]="form">
<div class="row">
<select class="select form-control" formControlName="environment_id_1">
<option value="">Select Environment 1 </option>
<option *ngFor="let environment of environments1" [value]="environment.environment_id"> {{environment.environment}} </option>
</select>
</div>
<div class="row" style="padding-top: 10px;">
<select class="select form-control" formControlName="environment_id_2">
<option value="">Select Environment 2 </option>
<option *ngFor="let environment of environments2" [value]="environment.environment_id"> {{environment.environment}} </option>
</select>
</div>
enter image description here

Related

Get the value of a select option in Angular

i have this user.model.ts, Ihave a list of users that I can edit by clicking on a button that filters the user's data and puts it in a modal of bootstrap, with the [ngModel] in select tag i can get the country of my user but when i change the country and submit the form I receive the current country but not its id, it should be noted that when I use [value] in the option it does not show me the current country, how can i get the value and not the name? Thanks.
in user.component.ts
updateUser(formActualizarTeam) {
console.log(this.user);
}
in user.model.ts
export class UserModel{
name: string;
idCountry: number;
}
in user.component.html
<form
#formUpdate="ngForm"
(ngSubmit)="updateUser(formUpdate)">
<select
id="country"
name="idCountry"
class="form-control"
[(ngModel)]="user.idCountry">
<option *ngFor="let c of countries">{{ c.name }}</option>
</select>
</form>
I think you need to use the [value] attribute to match the options to select ngModel
then the code will be (if you have idCountry in countries array)
<select id="country" name="idCountry" class="form-control [(ngModel)]="user.idCountry">
<option *ngFor='let c of countries' [value]='c.idCountry'>{{ c.name }}</option>
</select>
You need bind [value] to idCountry , also to set default value the selected value should match some option value :
<select
id="country"
name="idCountry"
class="form-control"
[(ngModel)]="user.idCountry">
<option *ngFor="let c of countries" [value]="c?.idCountry">{{ c?.name }}</option>
</select>
Also to load the default value there are two option:
component.ts
ngOnInit(){
this.user['idCountry'] = this.countries[0]['id']; // set this after country data is loaded
}
OR
this.user['idCountry'] = '';
component.html
<select
id="country"
name="idCountry"
class="form-control"
[(ngModel)]="user.idCountry">
<option value="" [disabled]="true"> Select country</option> // set some placeholder
<option *ngFor="let c of countries" [value]="c?.idCountry">{{ c?.name }}</option>
</select>
You have to set [value] for your option tag like below [value]="c.idCountry"
<form
#formUpdate="ngForm"
(ngSubmit)="updateUser(formUpdate)">
<select
id="country"
name="idCountry"
class="form-control"
[(ngModel)]="user.idCountry">
<option *ngFor="let c of countries" [value]="c.idCountry">{{ c.name }}</option>
</select>
</form>
you will get value now try priting it
updateUser(ngform){
console.log(ngform.form.value)
}
You can get selected value by using (change) event.
In your html:
<select (change)="onChange($event)"
id="country"
name="idCountry"
class="form-control">
<option *ngFor="let c of countries">{{ c.name }}</option>
</select>
In you .ts:
onChange(e: any) {
console.log(e.target.value);
}

Disabling a lowest value from dropdown

I have a dropdown list array which is shown in my UI How can I disable all highest elements in array and I want to enable only the lowest value in array
<select class="select-option" name="tier" required [ngModel]="tierDropDown">
<option value="select Tier" selected>Select Tier</option>
<option class="option" *ngFor="let tier of tierList" let i="index" value="{{tier}}" [disabled]="arr">
{{ tier }}
</option>
</select>
.TS file:
tierList = ["Tier1", "Tier2", "Tier3", "Tier4", "Tier5"]
this.arr = [];
let min = this.tierList;
this.arr = min.sort();
this.arr.splice(this.arr[0], 1);
console.log(this.arr);
this.arr.splice(this.arr[0], 1);
console.log(this.arr);
this will return splicing lower element and all higher elements so I am binding that value in [disabled] property in HTML file but the result is all my dropdown values are disabled
You can store the lowest value from array in a local variable and then use for that variable for [disabled] attribute:
HTML Code:
<select class="select-option" name="tier" required [ngModel]="tierDropDown">
<option value="select Tier" selected>Select Tier</option>
<option class="option" *ngFor="let tier of tierList" let i="index" value="{{tier}}" [disabled]="tier != LowestValue">
{{ tier }}
</option>
</select>
TS:
#Component({
selector: 'select-overview-example',
templateUrl: 'select-overview-example.html',
styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
tierList = ["Tier1", "Tier5", "Tier3", "Tier4", "Tier2"]
LowestValue: any;
constructor() {
this.LowestValue = this.tierList.sort()[0];
}
}
Working_Demo
There seems to be a much easier way to do this than the answers provided here. ngFor has exported values that can be aliased to local variables (Source: docs). We can use the first local variable to disable all elements but the first in the dropdown.
As per the docs
first: boolean: True when the item is the first item in the iterable.
With this in mind, we can disable every value that is not the first item in the dropdown using [disabled]="!first"
Here's how your HTML will now look
<select class="select-option" name="tier" required [ngModel]="tierDropDown">
<option value="select Tier" selected>Select Tier</option>
<option class="option" *ngFor="let tier of tierList; let first = first" value="{{tier}}" [disabled]="!first">
{{ tier }}
</option>
</select>
Then in your component just sort tierList.
[disabled] should bind to a boolean. Now you are binding it to an array arr. So it Will always be true. The arr exists. I don’t understand completely what you want to do but if you add en object to your tierList you could calculate an property isDisabled for every element and bind that to the disabled.
Ex: {name:tier1,disabled:true}
You can use the following answer ,
Your html file
<select class="select-option" name="tier" required >
<option value="select Tier" selected>Select Tier</option>
<option class="option" [disabled]="arr" *ngIf="arr">
{{arr}}
</option>
<option class="option" *ngFor="let tier of tierList" let i="index" value="{{tier}}" >
{{ tier }}
</option>
</select>
In .ts file ,
tierList =["Tier1","Tier2","Tier3","Tier4","Tier5"];
arr = [];
let min = this.tierList;
this.arr = min.sort();
this.arr.splice(this.arr[0], 1);
this.arr = this.arr.splice(this.arr[0], 1);
this.arr = this.arr[0]
console.log(this.arr[0]);
console.log(this.tierList);
This answer will work for you.

dynamic row creation affecting other created dropdown values angular 6

I have 3 drop downs primary, secondary,ternary categories, each dependent on each other, Initially I have 3 drop downs below that I have one button " add more" , after clicking "add more" again drops will come below the ones earlier have, now the question is first row drop down selection is working fine , after clicking "add more" the second row drop down selection is not working , means it changes the value of already selected first row of the second category same with the ternary category. first I all load all the primary category, based on primary id i will fetch secondary categories, based on the secondary category id i will fetch ternary category. please me with this.
HTML CODE
<div class="row Space_2">
<div class="col-md-4">
<select class="Textfield_2" id="primary_category_id" formControlName="primary_category_id" (change)="getSecondCategory($event.target.value)" name="primaryServices" required>
<option value="">Primary Service</option>
<option *ngFor="let primaryCat of primaryCategory" [value]="primaryCat.id">{{primaryCat.name}}</option>
</select>
</div>
<div class="col-md-4">
<select class="Textfield_2" id="secondary_category_id" formControlName="secondary_category_id" (change)="getTernaryCategory($event.target.value)" name="secondaryServices" required>
<option value="">Secondary Service</option>
<option *ngFor="let secondCat of secondCategory" [value]="secondCat.id">{{secondCat.name}}</option>
</select>
</div>
<div class="col-md-4">
<select class="Textfield_2" id="ternary_category_id" formControlName="ternary_category_id" name="secondaryServices" required>
<option value="">Ternary Service</option>
<option *ngFor="let ternaryCat of ternaryCategory" [value]="ternaryCat.id">{{ternaryCat?.name}}</option>
</select>
</div>
</div>
<div *ngFor="let k of addmoreServices let i = index">
<div class="row Space_2">
<div class="col-md-4">
<select class="Textfield_2" id="primary_category" (change)="getSecondCategory($event.target.value)" name="{{k.primary_category}}" required>
<option value="">Primary Service</option>
<option *ngFor="let a of primaryCategory" [value]="a.id">{{a?.name}}</option>
</select>
</div>
<div class="col-md-4">
<select class="Textfield_2" id="secondary_category" (change)="getTernaryCategory($event.target.value)" name="{{k.secondary_category}}" required>
<option value="">Secondary Service</option>
<option *ngFor="let b of secondCategory" [value]="b.id">{{b?.name}}</option>
</select>
</div>
<div class="col-md-4">
<select class="Textfield_2" id="secondary_category" (change)="getTerId($event.target.value)" name="{{k.ternary_category}}" required>
<option value="">Ternary Service</option>
<option *ngFor="let c of ternaryCategory" [value]="c.id">{{c?.name}}</option>
</select>
</div>
</div>
</div>
TypeScript Code:
getPrimaryCategory() {
this.http.get('http://localhost:3000/api/getPrimaryCategory' ,{
})
.subscribe(
res => {
this.primaryCategory = res['data'];
console.log(this.primaryCategory);
},
err => {
}
);
}
getSecondCategory(id,i) {
this.primcatId = id;
this.http.get('http://localhost:3000/api/getsecondarycatdataforternary/'+id ,{
})
.subscribe(
res => {
this.secondCategory = res['data'];
console.log(this.secondCategory);
},
err => {
}
);
}
getTernaryCategory(id) {
console.log("The ternary ID is",id);
this.secondId = id;
this.http.get('http://localhost:3000/api/getternaryCatforServices/'+id ,{
})
.subscribe(
res => {
this.ternaryCategory = res['data'];
console.log(this.ternaryCategory);
},
err => {
}
);
}
getTerId(id){
this.terid = id;
console.log("THE TERNARY ID IS",this.terid);
}
addMoreServices() {
this.addmoreServices.push({ primary_category:this.primcatId , secondary_category:this.secondId ,ternary_category: this.terid });
console.log("the add more services",this.addmoreServices);
}
You need to add trackBy to your *ngFor directives. You can track by id and thanks you this Angular won't treat values after refreshing as new values.

ngChange a bunch of dropdowns

So I need to entirely change a group of drop downs that appear based on the selection of one dropdown. I believe ngChange is the way to go about it, but I am not entirely sure how to change between two sets of divs (or if that is even the best way of doing it.
So I have this dropdown:
<div class="input-group" theme="bootstrap" style="">
<label>Product Type</label>
<select class="dropdown-menu scrollable-menu form-control" style="" ng-model="event.etype" ng-change="setOptions()" id="etype">
<option value="" selected disabled>Select a Product</option>
<option ng-click="type = 'x'">X</option>
<option ng-click="type = 'y'">Y</option>
<option ng-click="type = 'z'">Z</option>
<option ng-click="type = 'q'">Q</option>
<option ng-click="type = 'w'">W</option>
</select>
</div>
If the choice is X, I need one set of drop downs (contained in one row), and if it is anything else, I need an entirely different set (contained in another row).
Here are how the drop downs look:
<div class="col-lg-3">
<label>Numbers</label>
<ui-select-match placeholder="Select Numbers">{{$item.admin_user.name}}</ui-select-match>
<ui-select-choices repeat="a in ams"> {{a.admin_user.name}} </ui-select-choices>
</ui-select>
</div>
</div>
<div class="row col-lg-12" id="nonX">
<div class="col-lg-3">
<div class="input-group" theme="bootstrap">
<label>Super Heroes</label>
<select class="dropdown-menu scrollable-menu form-control" ng-model="superhero" id="script">
<option value="" selected disabled>Select Superhero</option>
<option ng-repeat="superhero in superheroes" ng-value={{superhero}} ng-click="selectHeroe(superhero)">{{superhero.name}}</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="row col-lg-12" id="noniPad">
<div class="col-lg-3">
<div class="input-group" theme="bootstrap">
<label>Screen</label>
<select class="dropdown-menu scrollable-menu form-control" ng-model="event.screen" id="screen">
<option value="" selected disabled>Select Screen</option>
<option ng-repeat="screen in screens" ng-value={{screen}} ng-click="selectScreen(screen)">{{screen.name}}</option>
</select>
</div>
</div>
<div class="col-lg-3">
<div class="input-group" theme="bootstrap">
<label>Misc Asset</label>
<select class="dropdown-menu scrollable-menu form-control" ng-model="event.miscasset" id="miscasset">
<option value="" selected disabled>Select Misc Asset</option>
<option ng-repeat="miscasset in miscassets" ng-value={{miscasset}} ng-click="slectMiscAsset(miscasset)">{{miscasset.name}}</option>
</select>
</div>
</div>
</div>
<div class="row m-b-sm m-t-sm"></div>
</div>
The separate drop downs both appear in different rows. So I would need one row to appear if they select iPad and one row to appear if they do not select an iPad.
I would love some help. Thank you!
Your best option would be to set the dropdowns of each one depending on the parent selection. There's no need to create a duplicate div to hold both sets of dropdows.
I removed all css classes and any other markup not relevant to the ng-change to make it clearer.
Your parent dropdown would look like this:
<div>
<label>Product Type</label>
<select ng-model="event.etype" ng-change="setOptions(event.etype)">
<option value="">Select a Product</option>
<option ng-repeat="etype in etypes" ng-value="etype" ng-bind="etype"></option>
</select>
</div>
Take special notice of how the setOptions handler is being passed the ng-model value. This means when an option is selected, it'll automatically set ng-model="event.etype" to the value of that option.
To support this behavior in your controller you need to provide the array of event types:
$scope.etypes = ['gif', 'photo', 'ipad', 'video', 'print'];
Then, on your setOptions method you'll get the selected option and filter your descendant dropdowns
var options1 = [{
etype: 'ipad',
value: '1'
}, {
etype: 'gif',
value: '2'
}];
$scope.setOptions = function (etype) {
$scope.scripts = options1.filter(function (item) {
return item.etype == etype;
});
};
What this means is that setOptions will set the descendant dropdowns based on the etype value passed in. In this example I'm limiting to $scope.scripts only but you can set as many as needeed. As you can see options1 is just an array which contains the etype property which I need to filter against.
Finally on your descendant dropdowns you would use the filtered options:
<select ng-model="event.script">
<option value="" selected disabled>Select Script</option>
<option ng-repeat="script in scripts" ng-value="script.value" ng-bind="script.value"></option>
</select>
Using ng-hide="event.etype == null || event.etype=='ipad'" and ng-show="event.etype == 'ipad'" on the row tags solved my issue!

Not getting default selected value of drop down list using angular.js

i am not getting the default value of my drop down list using angular.js. i am explaining my code below.
<th>
<select style="width:100%; border:none; font-weight:bold;" ng-options="sub.name for sub in noCourse track by sub.value" ng-model="search" ng-change="selectedCourseTable();" >
<option value="">Course Name</option>
</select>
</th>
Here I am fetching the data dynamically and bind them in select tag.The above code generates the following html output.
<select style="width:100%; border:none; font-weight:bold;" ng-options="sub.name for sub in noCourse track by sub.value" ng-model="search" ng-change="selectedCourseTable();" class="ng-valid ng-touched ng-dirty ng-valid-parse">
<option value class selected="selected">Course Name</option>
<option value="Master of computer application" label="Master of computer application">Master of computer application</option>
<option value="Bachelor of Technology" label="Bachelor of Technology">Bachelor of Technology</option>
<option value="Master in Technology" label="Master in Technology">Master in Technology</option>
</select>
subjectController.js:
$scope.selectedCourseTable=function(){
if($scope.search.value=='Bachelor of Technology'){
alert($scope.search.value);
}
if($scope.search.value=='Master in Technology'){
alert($scope.search.value);
}
if($scope.search.value=='Master of computer application'){
alert($scope.search.value);
}
if($scope.search==''){
alert($scope.search.value);
}
}
Here I can not check when i am selecting text as Course Name in ng-change event.Other select option i can check by using this line $scope.search.value but when user is selecting this default text Course Name it can not be check.Please help me to resolve this issue.
Removing the <option value="">Course Name</option> in your template and adding a corresponding default selection in your object list will fix this.
Wherever you set your noCourse:
$scope.noCourse = [{
name :'Course Name',
value: ''
}, /*rest of the values*/];
$scope.search = $scope.noCourse[0];
You would then need to modify the line before to now check the object:
// instead of this:
if ($scope.search == '') {
alert($scope.search.value);
}
// do this
if ($scope.search.value == '') {
alert($scope.search.value);
}

Categories

Resources