I have a select element in my component template that is hooked up a selectedEmp model.I want to be able to update the selectedEmp in the component and have the correct value show in the select element. My current setup is not letting this happen. Instead the select value does not display the selectedEmp. I console logged the selectedEmp, and its value is changing. I think this is because the option element is never set to any value when i do it via the component. Does anyone know a way to do this.
Component.html
<select name="sel1" class="form-control" (ngModelChange)="onChange($event.target.value)" [(ngModel)]="selectedEmp">
<option [value]="employee" *ngFor="let employee of employees">
{{employee}}
</option>
</select>
Component.ts
employees:Array<string> = ["Andrew","Allen","Kevin","Phil"];
visable:boolean = false;
selectedEmp:any = null;
constructor(){}
// Selection change
onChange(value:any):void {
console.log(value);
}
updateModel(){
this.selectedEmp = "Allen"
}
It's not quite clear from your question but I did see one error on your (ngModelChange) event binding, since the items are strings, $event.target.value fails try (ngModelChange)="onChange($event)".
But that was only for console anyway, so removing it leaves:
<button type="button" (click)="updateModel()">Select Allen</button>
<select name="sel1" [(ngModel)]="selectedEmp">
<option [value]="employee" *ngFor="let employee of employees">
{{employee}}
</option>
</select>
Related
For some reason, change is not detected on the select element in Angular reactive form. Below is the code extract
Component html code
<form (ngSubmit)="onSubmit()" [formGroup]="postProjectForm">
<div class="form-group">
<label>Job Type:</label>
<select formControlName="jobType" (change)="onChange($event.target.value)" >
<option *ngFor="let jt of jobTypes" [value]="jt">{{jt}}</option>
</select>
</div>
</form>
Component js code
jobTypes = ['Full time', 'Part time', 'Intership', 'Freelancing'];
constructor(private fb: FormBuilder){
this.postProjectForm = this.fb.group({jobType: new FormControl(this.jobTypes[0])})
}
onSubmit() {
console.log(this.postProjectForm.get('jobType').value);
}
onChange(val){
console.log(val);
}
The code starts fine, i.e. the select is populated with three four values with 'Full Time' as default value. However, when I change the option and submit, the onSubmit method logs the initial value ( Full Time ).
Also the onChange method does not fire at all!
Try updating: <select formControlName="jobType" (change)="onChange($event.target.value)" >
to <select formControlName="jobType" (change)="onChange($event.target)" >
and onChange(val){ console.log(val); } to onChange(val){ console.log(val.value); } and see if the onChange event now works. If this works, then the form should also work. I don't see any other reason why it won't.
If so, I can probably explain what's happening.
[For some reason the selected select option not showing any value just a blank area only when clicking it it shows the values. ive checked the css files and it seems fine no idea what causes the problem when i remove the [(ngModel)] it works but not getting the values =/
import { Component, OnInit } from '#angular/core';
import { Company } from '../_models/company';
import { CompanyService } from '../_services/company.service';
import { AlertifyService } from '../_services/alertify.service';
#Component({
selector: 'app-company',
templateUrl: './companies.component.html',
styleUrls: ['./companies.component.css']
})
export class CompaniesComponent implements OnInit {
selectedCompany: Company;
companies: Company[];
constructor(private companyService: CompanyService, private alertify: AlertifyService) { }
ngOnInit() {
this.loadCompanies();
}
async loadCompanies() {
this.companyService.getCompanies().subscribe((companies: Company[]) => {
this.companies = companies;
}, error => {
this.alertify.error(error);
});
}
// selectedChangeHandler(event: any) {
// this.selectedCompany = event.target.value;
// }
}
<ng-container *ngIf="companies">
<div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
<label for="">Select Company</label>
<select class="form-control" [(ngModel)]="selectedCompany" >
<option selected> -- select an option -- </option>
<option *ngFor="let value of companies" [ngValue]="value">{{value.name}}</option>
</select>
</div>
</ng-container>
<!--Just a test--->
<!-- <select class="form-control col-lg-8" #selectedValue name="selectedValue" id="selectedValue" [(ngModel)]="company" (ngModelChange)="assignCorporationToManage($event)">
<option *ngFor="let value of companies" [ngValue]="company">{{value.name}}</option>
</select> -->
<ul *ngIf="selectedCompany" class="list-group list-group-flush">
<li class="list-group-item">Company name: {{selectedCompany.name}}</li>
<li class="list-group-item">Company address: {{selectedCompany.address}}</li>
<li class="list-group-item">Company estimated revenue: {{selectedCompany.estimatedRevenue}}₪</li>
</ul>
I see several issues with your example, so I am going to offer another approach, and explain what I am doing along the way.
In an Angular application, when using two way binding with [(ngModel)] on a select, the initially selected option will always be set to the one that matches the value of ngModel.
In your example, the initial value for selectedCompany is never set, and that is the reason your initial page load displays the menu with nothing selected. You are going to need to set a value onto all of your options, including the first to get this to work.
Now, since you did not provide the structure of your model titled Company, I am going to improvise and assume it contains two elements, name and value. So just remember, you will need to adjust what I have below to match the actual structure of your data.
First, on the option tags in your select in the template, id suggest using the value attribute which we will be populating with strings, instead of ngValue which is can be used to contain an object or a string. You can obtain the object that contains all of the data you need via the change event later.
Let's adjust your template file as follows:
<select class="form-control" [(ngModel)]="selectedCompany" (change)="companyChange($event.target.value)">
<option [value]="'init'">-- select a company --</option>
<option *ngFor="let company of companies" [value]="company.value">{{company.name}}</option>
</select>
Next, in your component file, lets change that property that we're using for two way binding on your select to be typed as a string:
selectedCompany:string;
Next, lets create a new property typed to your model which we will ultimately set to the company selected:
myCompany:Company;
Next, set the initially selected option in your component so that '-- select a company --' will display as the initially selected option:
ngOnInit() {
this.selectedCompany = 'init';
this.loadCompanies();
}
And lastly, inside the change event, you can use the find() method to obtain the complete set of data that you need:
companyChange(value) {
this.myCompany = this.companies.find(element => element.value === value);
console.log("User selected the company:", this.myCompany);
}
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
I am trying to set default value of select option with Angular 7, but it doesnt set default option value;
Here what I tried to do.
At the component I am using setValue() method to set default value.
this.courseForm.controls['selectedTeacher'].setValue(this.course['Teacher'],{onlySelf: true});
And at the template I am using select like this:
<select formControlName="selectedTeacher">
<option *ngFor="let teacher of teachers" [ngValue]="teacher">
{{ teacher.FirstName }} {{teacher.LastName}}
</option>
</select>
Normally when try like this with input text it works but select list doesnt work.
I couldn't realize exactly what the problem is.
Help please,
Thanks
Angular uses objects reference, instead of properties, so if you do this, it will work if you have unique identifier for each teacher
const teacher = this.teachers.find(t=> t.id == this.course['Teacher'].id);
this.courseForm.controls['selectedTeacher'].setValue(teacher,{onlySelf: true});
Or you can find by any unique property
const teacher = this.teachers.find(t=> t.FirstName == this.course['Teacher'].FirstName && t.LastName == this.course['Teacher'].LastName );
change in your component:
this.courseForm.controls['selectedTeacher'].setValue(this.course['Teacher'].id,{onlySelf: true})
in your html:
<select formControlName="selectedTeacher">
<option *ngFor="let teacher of teachers" [value]="teacher.id">
{{ teacher.FirstName }} {{teacher.LastName}}
</option>
</select>
my values are been printing in a alert, but how can I print this value in my DOM? like in a h1 tag?
app.html:
<template>
<select value.bind="changedValue" change.delegate="DropdownChanged(changedValue)">
<option model.bind="1">1</option>
<option model.bind="2">2</option>
<option model.bind="3">3</option>
<option model.bind="4">4</option>
</select>
</template>
app.js
export class App {
changedValue;
DropdownChanged(changedVal) {
alert(changedVal);
}
}
https://gist.run/?id=87f6897928feb504dad638d439caf92f
Your changedValue in App holds the model you select as I see it.
You just need to give it a default (and maybe a better name)
export class App {
value = 1;
Then update it when a different value is selected instead of alerting.
DropdownChanged(changedVal) {
this.value = changedVal;
}
Then you can freely use it in your template
<template>
<h1>${value}</h1>
...
As suggested, you might not need the change interceptor at all, in which case you can just bind to the select's model:
<select value.bind="selectedValue">
and
<h1>Selected Value: ${selectedValue}</h1>
(no need for any js code in this particular simplified example)