I am using angular 6 and i am unable to display the selected option as default in select box,
HTML consists,
<select class="form-control selectBox" name="username" #username="ngModel" required ngModel>
<option disabled selected>Select User Name</option>
<option *ngFor="let user of userList" [value]="user.uid">{{user.name }}</option>
</select>
Ts:
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
userList: any = [
{
"name" : "Test User"
},
{
"name" : "Hello World"
},
{
"name" : "User Three"
}
]
}
It is showing empty value as default inside the select box.
How can i show the selected option as default inside the select box which from the line?
<option disabled selected>Select User Name</option>
Stackblitz:https://stackblitz.com/edit/angular-wfjmlm
You need to set a value in select box like this:
<option disabled selected value="">Select User Name</option>
Will make it work.
add [value]=""
<option disabled [value]="" selected>Select User Name</option>
and if you want to hide disable option then add hidden attribute
<option hidden disabled [value]="" selected>Select User Name</option>
the solution can be found in as follows
following was html
<select class="form-control selectBox" name="username" [(ngModel)]="selected" required>
<option disabled selected>Select User Name</option>
<option *ngFor="let user of userList" >{{user.name }}</option>
</select>
<hr> {{selected}}
following was the controller
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
userList: any = [
{
"name": "Test User"
},
{
"name": "Hello World"
},
{
"name": "User Three"
}
];
selected = 'Select User Name';
}
stackblitz
ReactiveForms
I pretty much suggest using ReactiveForms. In this way you will have a cleaner code as well as more powerful options.
first import ReactiveForms to your app.module:
import {FormsModule, ReactiveFormsModule} from '#angular/forms';
...
imports: [
...
ReactiveFormsModule
...
]
Then in your controller:
myForm: FormGroup;
constructor(private fb: FormBuilder){
this.myForm = this.fb.group({
username: null
})
}
And in your template:
<form [formGroup]="myForm">
<select formControlName="username" placeholder="Select Username">
<option disabled selected>Select User Name</option>
<option *ngFor="let user of userList" [value]="user.uid">{{user.name }}</option>
</select>
Use angular material instead of select and option.
Like this for example:
<mat-form-field>
<mat-select placeholder="Select User Name">
<mat-option *ngFor="let user of userList" [value]="user.uid">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
More details here: https://material.angular.io/components/select/overview
Related
I have two select and I show value if they exist:
page.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
customer: any = {
city: '',
state: '',
};
ngOnInit() {
// I recover this info from BE
this.customer.state = 'England';
this.customer.city = 'London';
}
}
page.html
<div class="col configurator-form-input col-12 col-md-6">
<label class="text">State *</label>
<div
class="input-group input-error"
[ngClass]="
customer.state ? 'input-group input error' : 'input-group input-error'
"
>
<select
id="state"
class="form-control"
[(ngModel)]="customer.state"
[ngModelOptions]="{ standalone: true }"
(change)="onChangeProvinceForState($event.target.value)"
appTab
tabIndex="14"
>
<option disabled value="">Select State</option>
<option
*ngFor="let state of stateList"
ngDefaultControl
[value]="state.name"
>
{{ state.name }}
</option>
</select>
</div>
</div>
<div class="col configurator-form-input">
<label class="text">City *</label>
{{ this.customer.city }}
<div
class="input-group input-error"
[ngClass]="customer.city ? 'input-group' : 'input-group input-error'"
>
<!-- <span class="fake-option" *ngIf="existingCustomer">{{customer.city}}</span> -->
<select
id="city"
name="city"
class="form-control"
[(ngModel)]="customer.city"
[ngModelOptions]="{ standalone: true }"
appTab
tabIndex="15"
>
<option value="">Select City</option>
<option *ngFor="let city of citiesList" ngDefaultControl [value]="city">
{{ city }}
</option>
</select>
</div>
</div>
https://stackblitz.com/edit/angular-wyendp?file=src/app/app.component.html
I recover the city and state from an api call, but I don't understand how to show in the select directly
EDIT:
onChangeStateForCity(e) {
console.log("e ", e)
let countiesObservable = this.citiesService.getAllState();
countiesObservable.pipe(untilDestroyed(this)).subscribe((data: any) => {
this.citiesList = data[e];
});
}
You are missing the declaration of properties stateList and citiesList. I have modified your SB, to generate some static dropdown down options. You can easily assign these variables to the response you get from your API.
Stackblitz demo
app.component.ts (defined the variables):
stateList = [
'England',
'France'
]
citiesList = [
'London',
'Paris'
]
app.component.html (bind them in template):
<option *ngFor="let state of stateList" ngDefaultControl [value]="state">
<option *ngFor="let city of citiesList" ngDefaultControl [value]="city">
Just add array of stateList and citiesList.
stateList = [{ name: 'England' }];
citiesList = ['London'];
I am using an input box with HTML5 datalist. Once the user enters some text and clicks the search icon/button, it fetches data which I want to show as dropdown/datalist suggestions. How can I do this? Here is my code (I use Angular 6):
import { Component, ViewChild, ElementRef } from '#angular/core';
#Component({
selector: 'my-app',
template: `
<div class="group">
<input #name list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
<button (click)="editName()">Edit</button>
</div>
`,
styleUrls: ['./app.component.scss']
})
export class AppComponent {
#ViewChild("name") nameField: ElementRef;
editName(): void {
this.nameField.nativeElement.focus();
}
}
You can use filter and array to do this
import {Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
text:string='';
options =['Internet Explorer','Firefox','Chrome','Opera','Safari'];
show=this.options;
editName(): void {
this.show= this.options.filter(x=>x.includes(this.text));
}
}
<div class="group">
<input [(ngModel)]='text' #name list="browsers">
<datalist id="browsers">
<option *ngFor="let opt of show" value="{{opt}}">
</datalist>
<button (click)="editName()">Edit</button>
</div>
Click to view example
I need to display a set of color box in select tag dropdown like below.
I tried it like below
<select>
<option value="">Choose Color</option>
<option value="red"><div class="color-box" style="background-color: #FF850A;"></div></option>
<option value="green"></option>
<option value="blue"></option>
<option value="yellow"></option>
</select>
But Its not working. Is there any library available for this? Kindly suggest.
I guess this is what you are looking for.
The color of the select box changes to the color of the option selected.
APP.COMPONENT.TS
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
selectedColor = '';
colors = [
{
name: 'yellow',
value: '#ffff00'
},
{
name: 'red',
value: '#ff3300'
},
{
name: 'blue',
value: '#0000ff'
}
];
onChange(value){
this.selectedColor = value;
}
}
APP.COMPONENT.HTML
<select (change)="onChange($event.target.value)" [ngStyle]="{'background-color':selectedColor}">
<option *ngFor="let color of colors" [value]="color.value" [ngStyle]="{'background-color':color.value}"></option>
</select>
Running code: https://stackblitz.com/edit/angular-rzb4rg
Advantages of creating a list in the component itself is that you can add or edit as many options as possible without changing the HTML and this is how we use it in our production also.
you can use [ngStyle]
I have create a demo on Stackblitz
component.html
<select>
<option *ngFor="let datas of data" [ngStyle]="{'background-color': datas.color}">{{datas.name}}</option>
</select>
component.ts
data=[{
name:'Red',
color:'red'
},{
name:'green',
color:'#008000'
}]
Just apply your style to the option tag, and it should work as intended :
<select>
<option value="">Choose Color</option>
<option value="red" style="background-color: #FF850A;"></option>
<option value="green"></option>
<option value="blue"></option>
<option value="yellow"></option>
</select>
Codepen here
What you can do is write the background color for option. See the code below!
<option value="">Choose Color</option>
<option style="background-color: #FF850A;" value="red"></option>
<option value="green"></option>
<option value="blue"></option>
<option value="yellow"></option>
When you create a select with ngFor loop for options, default value from ngModel is not selected
HTML :
<form style="margin : 20%;">
<div class="row">
<div class="form-group">
<label for="foo">K1 :{{keyboard | json}}</label>
<select [(ngModel)]="keyboard" name="foo" class="custom-select">
<option *ngFor="let a of foo" [ngValue]="a">{{a.name}}</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="fooz">K2 :{{keyboard2 | json}}</label>
<select [(ngModel)]="keyboard2" name="fooz" class="custom-select">
<option [ngValue]="foo[0]">AZERTY</option>
<option [ngValue]="foo[1]">QWERTY</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="fooa">K2 :{{keyboardStr | json}}</label>
<select [(ngModel)]="keyboardStr" name="fooa" class="custom-select">
<option [selected]="keyboardStr == 'AZERTY'" [ngValue]="AZERTY">AZERTY</option>
<option [selected]="keyboardStr == 'QWERTY'" [ngValue]="QWERTY">QWERTY</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="fooa">K2-bis :{{keyboardStr | json}}</label>
<select [(ngModel)]="keyboardStr" name="fooa" class="custom-select">
<option [selected]="keyboardStr == 'AZERTY'" [value]="AZERTY">AZERTY</option>
<option [selected]="keyboardStr == 'QWERTY'" [value]="QWERTY">QWERTY</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="fooa">K2-ter :{{keyboardStr | json}}</label>
<select [(ngModel)]="keyboardStr" name="fooa" class="custom-select">
<option [selected]="keyboardStr == 'AZERTY'" value="AZERTY">AZERTY</option>
<option [selected]="keyboardStr == 'QWERTY'" value="QWERTY">QWERTY</option>
</select>
</div>
</div>
</form>
Component :
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
private foo: any[] = [{id: 1, name: "AZERTY"}, {id: 2, name: "QWERTY"}];
private keyboard: any = {id: 1, name: 'AZERTY'};
private keyboard2 : any = {id: 1, name: 'AZERTY'};
private keyboardStr : string = 'AZERTY';
constructor() { }
ngOnInit() {
}
}
Result :
Shouldn't AZERTY be default selecteded ?
Is there a conflict when using both ngModel and ngValue ?
Because in the case of K1 example, value cannot be used as 'a' is an object right ?
Edit :
#Roy D. Porter Ok but imagine that I have this 'unit' object :
{
"id": 1,
"type": "REMISE",
"owner": "OWN",
"to": {
"id": 1,
"alone": true,
"level": 1,
"name": "Participant",
"minSales": 0.0,
"minTeamNumber": 0,
"durationCondition": 0,
"durationAwardCondition": null
},
"limit": 0.0,
"percentage": 25.0,
"alone": true
}
This will display well the type as model is a string :
<select [(ngModel)]="unit.type" name="tye" class="custom-select">
<option *ngFor="let type of types" [ngValue]="type">{{type | camelCase}}</option>
</select>
This does not display the default value it should :
{{award.name | camelCase}}
I assume this is caused by award not being a string. From what I see, ngModel is selected when it is a string but not when it's an object.
Angular v5.0.0
When you use [ngValue] on option, use [compareWith] on select.
Give it a function that compare two objects (in type of your ngValue and ngModel objects).
You have examples in the doc here : https://angular.io/api/forms/SelectControlValueAccessor
Best regards
I've faced the same issue as you.
My usual solution is to add an option to the list, and set it's value to -1, and initialise the binded variable to -1.
So in your case:
<select [(ngModel)]="keyboard" name="foo" class="custom-select">
<option value="-1">Please select an answer</option>
<option *ngFor="let a of foo" [ngValue]="a">{{a.name}}</option>
</select>
And in your component controller, initialise the keyboard variable to -1.
<select id="role" name="role" class="form-control" [(ngModel)]="user.role" #role="ngModel" required>
<option value="" >Select</option>
<option value="leadAnalyst">Lead Analyst</option>
<option value="analyst">Analyst</option>
<option value="assistant">Assistant</option>
</select>
user-create.component.ts
ngOnInit() {
this.user.role = 'Select';
}
I have tried using above code but its not working.
You need to define user as a object and then assign the value for the role,
export class AppComponent {
defaultStr = 'Select';
user = { role: this.defaultStr };
constructor() { console.clear(); }
getvalue(){
console.log(this.user.role);
}
}
WORKING DEMO
Change your code to :
ngOnInit() {
this.user.role = '';
}
For selecting the default value you need to use selected property of angular
<select id="role" name="role" class="form-control" #role="ngModel" required>
<option value="" >Select</option>
<option value="leadAnalyst" [selected]="'leadAnalyst' == user.role">Lead Analyst</option>
<option value="analyst" [selected]="'Analyst' == user.role">Analyst</option>
<option value="assistant" [selected]="'assistant' == user.role">Assistant</option>
</select>
"User.role" should return the role of user in ngOnInit()