aurelia.js print a value in my DOM from a select - javascript

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)

Related

Why does ngmodelChange event not fire when component loads on a dropdown?

In my Angular 8 component, I have added bi-directional binding to a dropdown control.
The view
<select (ngModelChange)='termSelectChanged($event)' [ngModel]="selected">
<option [ngValue]="t" *ngFor='let t of termsColl'>{{t?.code}}</option>
</select>
The component code
export class AppComponent implements OnInit{
public termsColl : Array<DDModel>;
public selected : DDModel;
constructor( private s : DDService ){}
termSelectChanged( event ){
alert('HIT');
}
ngOnInit(){
//service call #1
this.s.getDataForComplexBind().subscribe( data => {
this.termsColl = data;
}, error => error );
//service call #2
this.s.getOtherData( ).subscribe( data => {
//model changes here
this.selected = this.termsColl[1];
}, error => { console.error(error); });
}
}
When the component loads, it executes ngOnInit() and sets the model-bound property Selected with the first element of the array termsColl. termsColl has data but the line this.selected = this.termsColl[1]; does not change the selected option to the first element in the dropdown. In fact, when the component loads, I was expecting it to fire the event ngModelChange but it did NOT fire the event either. I have added an alert() in the code but it did not show when the component loads. It shows only if I select an option from the dropdown. How do I change the code so it will execute the ngModelChange event when the component loads?
Here is my stackblitz
https://stackblitz.com/edit/angular-version-yeg27j?file=src%2Fapp%2Fapp.component.ts
I changed the ngModeChange input to DDModel and called your termSelectChanged() from inside the subscribe. I also changed [ngModel] to [(ngModel)]
<select (ngModelChange)='termSelectChanged($event)' [(ngModel)]="selected">
<option [ngValue]="t" *ngFor='let t of termsColl'>{{t?.code}}</option>
</select>
termSelectChanged(selection: DDModel) {
console.log("HIT", selection);
}
ngOnInit() {
this.s.getOtherData().subscribe(
data => {
this.termsColl = data;
this.selected = this.termsColl[0];
this.termSelectChanged(this.selected);
},
error => {
console.error(error);
}
);
}
I can't tell you why changing this.selected from code does not trigger the ngModelChange. Maybe it's because ngModelChange is called in the template.
You can use viewToModelUpdate() of ngModel to update the value and if you want to trigger the ngModelChange. You can find more about it here.
But you need to do the following changes.
In html template:
<select (ngModelChange)='termSelectChanged($event)' [ngModel]="selected" #ngModel="ngModel">
<option [value]="t" *ngFor='let t of termsColl'>{{t?.code}}</option>
</select>
You can see I am adding a reference to the ngModel in template, which I will use it in the component class.
In the component class:
export class AppComponent {
name = "Angular 6";
version = VERSION.full;
public termsColl: Array<DDModel>;
public selected: string;
#ViewChild("ngModel") ngModel: NgModel;
constructor(private s: DDService) {}
termSelectChanged(event) {
this.selected = event;
}
ngOnInit() {
this.s.getOtherData().subscribe(
data => {
this.termsColl = data;
this.ngModel.viewToModelUpdate(this.termsColl[1]);
},
error => {
console.error(error);
}
);
}
}
You can see I am using the ngModel reference to call the viewToModelUpdate with the value, which in return triggers the ngModelChange.
Since you are not using two way binding directly, you have to set the value to the selected variable inside the trigger function termSelectChanged.
Hope this would help you to achieve your requirement.
You can use value instead of ngValue in you option elements. And assign t.code instead of t to the value attribute.
<select (ngModelChange)='termSelectChanged($event)' [ngModel]="selected">
<option [value]="t.code" *ngFor='let t of termsColl'>{{t?.code}}</option>
</select>
Reference: https://angular-version-xkjuff.stackblitz.io
termsColl has data but the code line this.selected = this.termsColl[1]; does not change the selected option to the first element in the drop down.
Because you are using propery binding [ngModel]="selected", not two-way data binding.
[(ngModel)]="selected" is for two-way binding, and the syntax is compound from:
[ngModel]="selected" and (ngModelChange)="selected = $event"
Also, the value of selected should be the value which is available in dropdown, i.e
ngOnInit(){
this.selected = this.termsColl[1].code
}
Below code would work for you:
<select [(ngModel)]="selected" (change)="onSelection()">
<option *ngFor='let t of termsColl' [value]="t.code" [selected]="selected === t.code">{{t?.code}}</option>
</select>
You might also want to refer this https://stackoverflow.com/a/63192748/13596406

Select selected option not working for some reason =/

[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);
}

Set default value option with Angular ReactiveForm setValue method

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>

How to access the selected option in React

In React JSX, I wrote below component:
<select //...
onChange={event => {alert(event.target); //setState}}
>
<option id=1>one</option>
<option id=2>two</option>
</select>
The alert gives me select element. How can I access selected option without jQuery? I am trying to setState on the id, and do corresponding searches and other things.
Instead of an id on select option, provide the value attribute you can then access it as event.target.value.
<select
onChange={event => {
alert(event.target.value);
}
}>
<option value="1"> one</option>
<option value="2"> two</option>
</select>
CodeSandbox
You wouldn’t typically access the value directly through the event target. Either bind the control value to component state or store a reference on the parent component... then you can access the value when the event is fired.
See: https://stackoverflow.com/a/47842562/1306026
You can access selected option like:
var elm = event.target;
console.log(elm.options[elm.selectedIndex]);
and then access its value or text like:
console.log(elm.options[elm.selectedIndex].value)
DEMO (change the option to see result):
function setState() {
var elm = event.target;
console.log(elm.options[elm.selectedIndex]);
console.log(elm.options[elm.selectedIndex].value);
}
<select onChange="setState()">
<option id=1>one</option>
<option id=2>two</option>
</select>

Angular2 - update select template from component

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>

Categories

Resources