[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);
}
Related
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
I need to Style:"text-decoration: line-through" on the second element of my array, how can i do that?
I tryed with CSS and with [ngStyle] but nothing worked.
My array is taken from an HTTP get request, but i don't think it change a lot.
In my TypeScript file i have the array of object but if i try to change the style there, nothing works.
TypeScript:
export class TypeObjectComponent implements OnInit {
object: Objects[];
constructor(
private route: ActivatedRoute,
private router: Router,
private service: ObjectService
) { }
ngOnInit() {
this.service.getType().subscribe(data => {
this.object= data;
})
}
HTML:
<div class="form-group">
<label for="typeO" ><b>Type</b></label>
<select value="E" class="form-control" id="single" name="type">
<option [ngStyle]="{'text-decoration': line-through}" *ngFor="let Objects of object; index as i">
{{i}} - {{ Objects.type}}
</option>
</select>
</div>
One issue is that, in your [ngStyle], you need quotes around the value line-through because, in that context, that's a JavaScript object value, not a CSS value.
That change should successfully apply text-decoration: line-through to your option elements.
However, that will probably not accomplish your goal of displaying your second item with a line through it (if I understand your goal correctly) because the option element within a select is a replaced element, so even with that style applied, the element will not display with a line-through. From MDN:
In CSS, a replaced element is an element whose representation is outside the scope of CSS; they're external objects whose representation is independent of the CSS formatting model...The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself.
So if you need custom styling on the dropdown options, you'll probably need to use something other than a select element.
Add a class on your 2nd element using the index value you have defined and write whatever styles you want to in your css file based on that class. For example see that edited part in html.
TypeScript:
export class TypeObjectComponent implements OnInit {
object: Objects[];
constructor(
private route: ActivatedRoute,
private router: Router,
private service: ObjectService
) { }
ngOnInit() {
this.service.getType().subscribe(data => {
this.object= data;
})
}
HTML:
<div class="form-group">
<label for="typeO" ><b>Type</b></label>
<select value="E" class="form-control" id="single" name="type">
<option [ngClass]="{'line-through': i === 1}" *ngFor="let Objects of object; let i=index;">
{{i}} - {{ Objects.type}}
</option>
</select>
</div>
IN YOUR CSS:
.line-though{
text-decoration: line-through;
}
I am grabbing some items through a http call and then want to pre-populate the ngselect, but using the abstractcontrol.setvalue() method does not seem to work.
Template Code
<ng-select [items]="cars"
bindValue="code"
bindLabel="displayName"
formControlName="car"
[clearable]="false"
[searchable]="false"
id="car"
placeholder="Select a car">
Component Code
this.setValueForPrePopulatedPlanningDetail('car', car);
private setDefaultValue(fieldName: string, value: any) {
if (value && value.length > 0) {
const field = this.myFormGroup.get(fieldName);
field.markAsDirty();
field.setValue(value);
}
}
You need set your result to the list (countries) and then use setvalue to choose the option
Set result to your list in your component:
this.countries = ['XPTO','XPTO2','XPTO3']
Define the following in your html:
<select>
<option [value]="country" *ngFor="let country of countries"> {{country}}</option>
</select>
The right way of using ng-select, would be to assign the values to the items input binding.
For instance,
<ng-select [items]="cities2"
bindLabel="name"
bindValue="id"
[multiple]="true"
placeholder="Select cities"
[(ngModel)]="selectedCityIds">
</ng-select>
And on your component.ts, you will populate ng-select options by subscribing to the observable returned by the HTTP request, and assigning it the cities2 property.
cities2: any[] = [];
ngOnInit() {
this.dataService.getData.subscribe(res => {
this.cities2 = res;
});
}
This demo might not directly answer your queries, but it shows how the various input bindings (such as items) work with ng-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)
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>