How to get full drop-down object item using Reactive Forms? - javascript

In this case I'm not using ngModel directives.
I want to know how to get the full object binded to the drop down when it change.
Basically, this is what I'm doing:
It's an array of objects with properties, but i don't want only the
value, i want the full object selected
<select #tipoTextoItem (change)="handleChange($item)" name="cmbTipoTexto" class="form-control form-control-sm col-sm-7" id="cmbTipoTexto" formControlName="cmbTipoTexto">
<option *ngFor="let item of textTypes" value="{{item.key}} {{item.value}}
</option>
</select>
Then...
handleChange($event) {
console.log($event.ForExampleGetMyObjectInThisWay());
}

You can use compareWith input property provided by angular. In the function you can compare and return the object. You can use it like:-
<select #tipoTextoItem (change)="handleChange($item)"
[compareWith]="compareFn"
name="cmbTipoTexto"
class="form-control form-control-sm col-sm-7"
id="cmbTipoTexto"
formControlName="cmbTipoTexto">
<option *ngFor="let item of textTypes"
value="{{item}}">{{item.value}}</option>
</select>
In your component.ts file,
compareFn(item1, item2) {
return item1 && item2 ? item1.value === item2.value : item1 === item1;
}
You can look into below link for more info:-
https://angular.io/api/forms/SelectControlValueAccessor#customizing-option-selection

you can use selectedIndex, Here you go :
(change)="handleChange($event.target.selectedIndex)" // change method
handleChange(index) {
console.log(this.textTypes[index]);
}
WORKING DEMO

Related

Angular 8 Select Option property binding

I have a Select Option Like This .. In this dropdown i am calling an api just to get some data
<div class="mb-frm_l frm_r">
<div class="dropdown inputs">
<select
[ngClass]="{
error:
billingForm.controls.selectDistrict.errors?.required &&
((billingForm.controls['selectDistrict'].dirty &&
billingForm.controls['selectDistrict'].touched) ||
billingForm.controls['selectDistrict'].errors
.isValidString)
}"
formControlName="selectDistrict"
id="selectDistrict"
(focus)="onFocus()"
(blur)="onBlur()"
(change)="getCityList($event.target.value)" // here i want to pass the District name
>
<option value="">Select District</option>
<option
*ngFor="let district of districtList"
[attr.district-id]="district.district_id"
[value]="district.district_id"
>
{{ district.district }}
</option>
</select>
<div
*ngIf="
billingForm.controls['selectDistrict'].invalid &&
billingForm.controls['selectDistrict'].dirty &&
billingForm.controls['selectDistrict'].touched
"
class="error_txt"
>
Please select state
</div>
</div>
</div>
Here I am passing the selected value in getCityList($event.target.value)
As i want the district.district also in my ts file
My Question is How can i pass the district.district here with the value also ???
Thanks!
A simple find in getCityList is what you need. Since you didnt provide the code, I made up something:
getCityList($event.target.value): void {
const value = '';
const district = this.districtList.find((d) => d.district_id === $event.target.value);
if (district) {
value = district.district;
}
}
Change your Option tag this [value]="district.district_id" into
[value]="district"
Then your (change)="getCityList($event.target.value)" will return selected district object. then you can access any property you want

Update value in select depending from other field in Angular 8

I'm trying to update the value in select in Angular 8.
I found that I can use:
$('#selectSeccion').val("SeccionOption");
This select is the next one:
<select name="seccion" class="form-control" id = "selectSeccion">
<option *ngFor="let seccion of seccion" [ngValue]="seccion">{{seccion.seccion}}</option>
</select>
jQuery code is not working when I use the select with Angular, only works when select is normal html like the next one:
<select class="form-control" id = "prueba">
<option value = ""></option>
<option value = "other">other</option>
</select>
How can I update the value on the "ng" select?
I would not recommend using jQuery along with Angular.
you can read more about it here: http://www.learnangularjs.net/using-jquery-with-angular.php
The simplest way
component.html:
<select [(ngModel)]="selectModel" (change)="selectionChange()">
<option [value]="seccion" *ngFor="let seccion of seccions"> {{seccion}}</option>
</select>
component.ts:
selectionChange() {
console.log(this.selectModel)
}
changing the selectModel parameter will trigger the select to change as well.
Based on previous recommendation I can updated using Angular, which always was the best way by the way. No jQuery. I have to change my select to the next one
<select name="seccion" class="form-control" id = "selectSeccion" [(ngModel)]="value" #ctrl="ngModel">
<option *ngFor="let seccion of seccion" >{{seccion.seccion}}</option>
</select>
Adding this on select tag > [(ngModel)]="value" #ctrl="ngModel" and updating the ts file with this lines:
value : string = '';
updatingFunction(){ this.value = "SeccionUpdated"; }
I left it if there someone needs it

AngularJS can't get selected index of dropdown menu

I have this dropdown menu:
<select class="form-control" name="timeSlot" ng-model="user.dateTimeSlot" ng-change="dateTimeChanged(user.dateTimeSlot)" ng-blur="blur29=true" required style="float: none; margin: 0 auto;">
<option ng-repeat="x in dateTimeSlots"
ng-disabled="x.taken"
ng-value="x.timeSlot">
{{x.dateSlot}}
</option>
</select>
And I am trying to get the selected index on the ng-change. However it always returns -1
$scope.dateTimeChanged = function (selectedItem) {
var index = $scope.dateTimeSlots.indexOf(selectedItem);
console.log(index);
}
Why is it always returning -1....here is a screenshot of my data:
What I am trying to do is get that id value on the selected item. What am I doing wrong?
Well, it is a little uncertain what you really want. Seems to me you are trying to run on two horses :) You bind the ng-model to timeSlot, but what you really want is the index so you easier can grab the object? What about binding the option values direct to the indexes? :
<option ng-repeat="x in dateTimeSlots"
ng-disabled="x.taken"
ng-value="{{ $index }}"> <!-- here -->
{{x.dateSlot}}
</option>
now user.dateTimeSlot will be 0,1,2,3 and so on (when an option is selected). In the change method you now receive the index
$scope.dateTimeChanged = function(selectedItem) {
console.log($scope.dateTimeSlots[selectedItem]) //<-- the selected object by index
}

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.

Categories

Resources