Angular5 select model - javascript

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>

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

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

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

Show default selection in Select dropdown - Angular

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

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.

angularjs nullable select if null then

I have in my html angularjs select with null posibility:
<span class="nullable">
<select ng-model="ViewLevel" ng-change="selChanged()"
ng-options="camptype.name for camptype in campTypes">
<option value="">-- choose campaign type --</option>
</select>
</span>
and in js controller method to check if user selected something from list or nullable option
$scope.selChanged = function() {
if ($scope.ViewLevel == null) {
$scope.getTypeData();
console.log("nullek");
} else {
$scope.getCampaignData();
console.log("nie nullek");
}
}
But it doesn't work. Always if clause is true, even if in firebug I can see that ViewLevel is not null. Why?
EDIT: screen from firebug
ViewLevel is an object with property but if clause was true:
rather than checking against null, using ! operator, it will check for both null/undefined
$scope.selChanged = function() {
if (!$scope.ViewLevel) {
$scope.getTypeData();
console.log("nullek");
} else {
$scope.getCampaignData();
console.log("nie nullek");
}
}
EDIT
as per angularjs recommendation: your ngModel must have a dot, and that would solve the problem for you.
//somewhere in your controller
$scope.selected = {}
and then in your html
<select ng-model="selected.ViewLevel" ng-change="selChanged()"
ng-options="camptype.name for camptype in campTypes">
<option value="">-- choose campaign type --</option>
</select>
and then again fix if in your function. check for $scope.selected.ViewLevel
$scope.selChanged = function() {
if (!$scope.selected.ViewLevel) {
$scope.getTypeData();
console.log("nullek");
} else {
$scope.getCampaignData();
console.log("nie nullek");
}
}

Categories

Resources