Dropdown can't pull number value from object (Angular 4) - json

I'm pulling data from an API, which is going fine unless I bind my JSON option number value into the [value] tag. see example:
WORKING (data got from API is selected on the option)
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension" [value]="c.name">{{ c.name }}</option>
</select> <!-- select with c.name on value -->
NOT WORKING (data is not selected and the first option is null)
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension" [value]="c.value">{{ c.name }}</option>
</select> <!-- select with c.value on value -->
JSON object:
subdimension = [{'name': 'sub1','value': 2 },
{'name': 'sub2','value': 4 },
{'name': 'sub3','value': 8}]
What I want to do is to bind a number value into some selects and then sum all of them like:
data.from.api.one + data.from.api.two...
EDIT:
Component code from the data.from.api
constructor (public dataService:DataService){
this.dataService.getData().subscribe(datas => {
this.datas = datas;
});
}
getData(){
return this.http.get('https://api.url/').map(res => res.json());
}
datas:Data[];
data = {
from:{api:{one:'',two:'',three:''}}
}

Everything works. i have created plunker. You need to setUp ngModel value after request.
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension; let i = index" [ngValue]="c">{{
c.name }}</option>
</select>
and if you want pure number
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension; let i = index" [value]="c.value">{{
c.name }}</option>
</select>
In your code use this code in ngOnInit hook
return this.http.get('https://api.url/').map(res => res.json()).do((d) => {
this.subdimension = d;
//if you use object
this.data.from.api.one = d[0]
//if you use value
this.data.from.api.one1 = d[0].value
})
or
this.dataService.getData().subscribe(datas => {
this.datas = datas;
this.data.from.api.one = datas[0]
//if you use value
this.data.from.api.one1 = datas[0].value
});

Related

Get id and value from selected Dropdown

i need id and value from selected dropdown. i tried things but not getting id, only value is coming. how do i get both id and value?
below is my code
.html
<div class="form-group">
<label>Item</label>
<select id='itemCode' name="" class="form-control">
<option value="" disabled selected>Choose Item</option>
<option *ngFor="let itemValue of itemslistvalue"
[ngValue]="{id: itemValue.itemCode, name: itemValue.itemName}">
{{itemValue.itemName}}
</option>
</select>
</div>
<div class="form-group"><br>
<button type="button" (click)="add()" style=" margin-left:10px;"></button>
</div>
.TS
add() {
var itemName = (<HTMLInputElement>document.getElementById('')).value;
var itemCode = (<HTMLInputElement>document.getElementById('')).value;
if (itemName !== null && itemName !== '' && itemCode !== null && itemCode !== '') {
this.newDynamic = { itemCode: itemCode, ItemName: itemName };
console.log(this.newDynamic);
this.dynamicArray.push(this.newDynamic);
return true;
}
}
just use a variable and ngModel
//In .ts
item:any=null;
<select id='itemCode' [(ngModel)]="item" name="" class="form-control">
<!--see that by defect is [ngValue]="null"-->
<option [ngValue]="null" disabled hidden>Choose Item</option>
...
</select>
And you has stored in item the value
You can call to change if it's necesary separate the [(ngModel)]
<select id='itemCode' [ngModel]="item"
(ngModelChange)="item=$event;doSomething($event)" name="" class="form-control">
...
</select>
//in your .ts
doSomething(item:any){
console.log(item);
}
If you don't want store the variable, use a template reference
<select #itemId id='itemCode' (change)="doSomething(itemId.value)"
name="" class="form-control">
...
</select>
If you use a template reference variable, you only can get the "value" of the select (in this case only the name)
<select #itemId id='itemCode' (change)="doSomething(itemId.value)"
name="" class="form-control">
...
</select>
doSomething(item:string){
console.log(item); //<--it's only the "name"
}
a stackblitz
the referecences:
about ngModel
about template reference variables
Update if we want to add a new element to the array, we declare two variables
newItemName:string=null;
newItemCode:string=null;
And in our .html
<input [(ngModel)]="newItemName">
<input [(ngModel)]="newItemName">
<button (click)="add()">Add</button>
Before the funciton add we need take account that when we use a select with store an object. WE can take two approach
1.-use a function compare, is only write some like
compareFn(a,b){
return !a && !b ||(a && b && a.itemCode==b.itemCode)
}
//or in abreviate mode:
compareFn=(a,b)=>!a && !b ||(a && b && a.itemCode==b.itemCode)
And in .html our select like:
<select [(ngModel)]="item" .. [compareWith]="compareFn">
2.- use the own elements of the array
<option *ngFor="let itemValue of itemslistvalue"
[ngValue]="itemValue">
{{itemValue.itemName}}
</option>
But in this case we need equal to an object of an array, e.g.
item=itemslistvalue[2]
Well, our function add, can use the values of the variables. this is the significance of two-binding-way, the value of the variable is in the input, when change the input the variable change
add() {
//see that inside a function you use "this"
if (this.newItemName && this.newItemCode) {
//if only want to add value if there no selecte any thing
//replace by
// if (this.newItemName && this.newItemCode && !this.item ) {..}
//try to find one with the same code
const item = this.itemslistvalue.find(
x => x.itemCode == +this.newItemCode
);
if (!item) { //if not find
//add
this.itemslistvalue.push({
itemCode: +this.newItemCode,
itemName: this.newItemName
});
//if we want that the select gets the value added
this.item = this.itemslistvalue[this.itemslistvalue.length - 1];
} else {
this.item = item; //just equal the element found
}
}
}
.Html
<div class="form-group">
<label>Item</label>
<select id='itemCode' name="" class="form-control">
<option value="" disabled selected>Choose Item</option>
<option *ngFor="let itemValue of itemslistvalue"
[ngValue]="{{{itemValue | json}}}">
{{itemValue.itemName}}
</option>
</select>
.Ts
add() {
var itemName = (<HTMLInputElement>document.getElementById('itemCode')).value;
console.log(itemName);
let myObj = JSON.parse(itemName);
itemCode = myObj.itemCode;
itemName = myObj.itemName;}

Angular 6 ngFor select object on a nested JSON

I am have a hard time trying to do an ngFor on nested JSON. I have read that ngFor is supposed to be for arrays only, but there are so many APIs that pump out nested JSON, that I figure that has to be a way.
The following is an example of the category JSON that I am receiving - I am simplifying what it could be:
{
"Categories": {
"candles": {
"name": "Candle"
},
"oils": {
"name": "Oil"
},
"chocolates": {
"name": "Chocolates"
},
"toys": {
"name": "Toys"
}
}
}
The following is an example of the http get:
this.http.get(this.jsonUriNestObj).subscribe(resultObj => {
this.categoryObj = resultObj["Categories"];
console.log(
"resultObj['Categories']: ",
JSON.stringify(resultObj["Categories"])
);
This would be an example of what comes back in the console:
resultObj['Categories']: {"candles":{"name":"Candle"},"oils":{"name":"Oil"},"chocolates":{"name":"Chocolates"},"toys":{"name":"Toys"}}
The following is what is currently not displaying any options in the select, but at the same time, zero errors and zero warnings:
<select id="categories" class="form-control">
<option value="">Please select an item</option>
<option
*ngFor="let item of this.categoryObj.name; let i = index"
value="{{ i }}"
>{{ item }}</option
>
</select>
I have tried this.categoryObj[i], this.categoryObj[i]['name'], etc...
How do I ngFor a nested JSON - hopefully, you can offer a dynamic solution.
As usual, thanks in advance and happy new year to you and yours
You can use keyValue pipe to iterate objects - I think this pipe is available from angular 6.1
Try something like this
<select id="categories" class="form-control">
<option value="">Please select an item</option>
<option
*ngFor="let item of this.categoryObj | keyvalue; let i = index"
value="{{ item.key }}"
>{{ item.value.name }}</option
>
</select>
I think this might help you - but make sure this pipe seems to be impure
For more info check this - Happy new year and happy coding :)
You are iterating over the object not array, array can be iterated easily.
You can use pipe to transform your objects to array or you can change your json object to array.
You need one new variable which can iterate easily and you can use it later, like this
name = 'Angular';
categoryObj = {"candles":{"name":"Candle"},"oils":{"name":"Oil"},"chocolates":{"name":"Chocolates"},"toys":{"name":"Toys"}}
outputData: any;
constructor(){
this.outputData = Object.keys(this.categoryObj).reduce((prev,curr)=>{
prev.push(this.categoryObj[curr].name);
return prev;
},[])
}
and in your view
<select id="categories" class="form-control">
<option value="">Please select an item</option>
<option
*ngFor="let item of this.outputData; let i = index"
value="{{ i }}"
>{{ item }}</option
>
</select>
EDIT:
As you want to iterate through object inside array, you can use
this.outputData = Object.keys(this.categoryObj).reduce((prev, curr) => {
prev.push(this.categoryObj[curr]);
return prev;
}, [])
this will give you array of objects
0: Object
name: "Candle"
1: Object
name: "Oil"
and you can bind it like this
<select id="categories" class="form-control">
<option value="">Please select an item</option>
<option
*ngFor="let item of this.outputData; let i = index"
value="{{ i }}"
>{{ item.name }}</option
>
</select>
Demo
Declare one variable to hold the revised JSON list:
list : any[] = [];
Just replace your get request with this:
this.http.get(this.jsonUriNestObj).subscribe(resultObj => {
this.categoryObj = resultObj["Categories"];
Object.keys(this.categoryObj).forEach(key => {
this.list.push(this.categoryObj[key])
})
});
HTML:
<select id="categories" class="form-control">
<option value="">Please select an item</option>
<option *ngFor="let item of list; let i = index" [value]="i">
{{ item.name }}
</option>
</select>
FORKED STACKBLITZ

DataList in Angular

I have a <datalist> and <select> as follows:
Updated:
Example 1:
<input type="text" list="codes" [(ngModel)]="codeValue" (change)="saveCode(codeValue)">
<datalist id="codes">
<option *ngFor="let c of codeList" [value]="c.code" >{{c.name}}</option>
</datalist>
<select type="text" list="codes" [(ngModel)]="codeValue1" (change)="saveCode(codeValue)">
<option *ngFor="let c of codeList" [value]="c.code" >{{c.name}}</option>
</select>
codeList Array in component.ts
codeList = [
{ code: 'abcdhe568dhjkldn', name: 'item1' },
{ code: 'ksdkcs7238t8cds', name: 'item2' },
{ code: 'kascggibebbi', name: 'item3' }
];
DataList is showing both name (c.name) and value (c.code) in the options and storing whatever is present in value whereas select is showing name (c.name) and storing value(c.code).
Behavior of datalist
Behavior of select
Example 2:
<datalist id="codes">
<option *ngFor = "let i of [1,2,3,4]" [value]="i">{{i-1}}</option>
</datalist>
{{a}}
I want to show the value of i-1 in the suggestion box but bind the variable 'a' with i.
Existing Solution in HTML
From this post Show datalist labels but submit the actual value I see that we can use "data-value" to
acheive the functionality in HTML. How can I achieve the same functionality in Angular.
Please help!
Thanks in advance.
Try Like this....
html File
<input type="text" list="codes" [(ngModel)]="codeValue" (change)="saveCode($event)">
<datalist id="codes">
<option *ngFor="let c of codeList" [value]="c.name" >{{c.name}}</option>
</datalist>
ts File
codeList = [
{ code: 'abcdhe568dhjkldn', name: 'item1' },
{ code: 'ksdkcs7238t8cds', name: 'item2' },
{ code: 'kascggibebbi', name: 'item3' }
];
public saveCode(e): void {
let name = e.target.value;
let list = this.codeList.filter(x => x.name === name)[0];
console.log(list.id);
}
Try it this way.
<option *ngFor = "let i of [1,2,3,4]" (change)="a=i" [value]="i">{{i-1}}</option>
Well, may someone correct me if I'm not telling the truth but you can't bind [value] to 'a', because then every option-element has the same value 'a'.
To achieve what you want you have to build an Array of objects that contain both fields, 'a' and 'i'. Then you can show 'i' and bind your value via ngModel to 'a'.
e.g.
in your component
export class AI {
constructor(
a: number,
i: number
) {}
}
aiList: Array<AI> = [];
ai: AI = new AI(1,0);
aiList.push(ai);
ai = new AI(2,1);
aiList.push(ai);
ai = new AI(3,2);
aiList.push(ai);
ai: = new AI(4,3);
aiList.push(ai);
in your template
<option *ngFor = "let ai of aiList" (change)="a=ai.a" [(ngModel)]="ai.a">{{ai.i}}</option>

Binding select element to object in Angular

I'd like to bind a select element to a list of objects -- which is easy enough:
#Component({
selector: 'myApp',
template:
`<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="#c of countries" value="c.id">{{c.name}}</option>
</select>`
})
export class AppComponent{
countries = [
{id: 1, name: "United States"},
{id: 2, name: "Australia"}
{id: 3, name: "Canada"},
{id: 4, name: "Brazil"},
{id: 5, name: "England"}
];
selectedValue = null;
}
In this case, it appears that selectedValue would be a number -- the id of the selected item.
However, I'd actually like to bind to the country object itself so that selectedValue is the object rather than just the id. I tried changing the value of the option like so:
<option *ngFor="#c of countries" value="c">{{c.name}}</option>
but this does not seem to work. It seems to place an object in my selectedValue -- but not the object that I'm expecting. You can see this in my Plunker example.
I also tried binding to the change event so that I could set the object myself based on the selected id; however, it appears that the change event fires before the bound ngModel is updated -- meaning I don't have access to the newly selected value at that point.
Is there a clean way to bind a select element to an object with Angular 2?
<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>
StackBlitz example
NOTE: you can use [ngValue]="c" instead of [ngValue]="c.id" where c is the complete country object.
[value]="..." only supports string values
[ngValue]="..." supports any type
update
If the value is an object, the preselected instance needs to be identical with one of the values.
See also the recently added custom comparison https://github.com/angular/angular/issues/13268
available since 4.0.0-beta.7
<select [compareWith]="compareFn" ...
Take care of if you want to access this within compareFn.
compareFn = this._compareFn.bind(this);
// or
// compareFn = (a, b) => this._compareFn(a, b);
_compareFn(a, b) {
// Handle compare logic (eg check if unique ids are the same)
return a.id === b.id;
}
This could help:
<select [(ngModel)]="selectedValue">
<option *ngFor="#c of countries" [value]="c.id">{{c.name}}</option>
</select>
You can do this too without the need to use [(ngModel)] in your <select> tag
Declare a variable in your ts file
toStr = JSON.stringify;
and in you template do this
<option *ngFor="let v of values;" [value]="toStr(v)">
{{v}}
</option>
and then use
let value=JSON.parse(event.target.value)
to parse the string back into a valid JavaScript object
It worked for me:
Template HTML:
I added (ngModelChange)="selectChange($event)" to my select.
<div>
<label for="myListOptions">My List Options</label>
<select (ngModelChange)="selectChange($event)" [(ngModel)]=model.myListOptions.id >
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption.id">{{oneOption.name}}</option>
</select>
</div>
On component.ts:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
An you need add to component.ts this function:
selectChange( $event) {
//In my case $event come with a id value
this.model.myListOptions = this.listOptions[$event];
}
Note:
I try with [select]="oneOption.id==model.myListOptions.id" and not work.
============= Another ways can be: =========
Template HTML:
I added [compareWith]="compareByOptionId to my select.
<div>
<label for="myListOptions">My List Options</label>
<select [(ngModel)]=model.myListOptions [compareWith]="compareByOptionId">
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption">{{oneOption.name}}</option>
</select>
</div>
On component.ts:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
An you need add to component.ts this function:
/* Return true or false if it is the selected */
compareByOptionId(idFist, idSecond) {
return idFist && idSecond && idFist.id == idSecond.id;
}
Just in case someone is looking to do the same using Reactive Forms:
<form [formGroup]="form">
<select formControlName="country">
<option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option>
</select>
<p>Selected Country: {{country?.name}}</p>
</form>
Check the working example here
In app.component.html:
<select type="number" [(ngModel)]="selectedLevel">
<option *ngFor="let level of levels" [ngValue]="level">{{level.name}}</option>
</select>
And app.component.ts:
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
levelNum:number;
levels:Array<Object> = [
{num: 0, name: "AA"},
{num: 1, name: "BB"}
];
toNumber(){
this.levelNum = +this.levelNum;
console.log(this.levelNum);
}
selectedLevel = this.levels[0];
selectedLevelCustomCompare = {num: 1, name: "BB"}
compareFn(a, b) {
console.log(a, b, a && b && a.num == b.num);
return a && b && a.num == b.num;
}
}
For me its working like this, you can console event.target.value.
<select (change) = "ChangeValue($event)" (ngModel)="opt">
<option *ngFor=" let opt of titleArr" [value]="opt"></option>
</select>
The key is to use a two way binding in the select via [(ngModel)] and use [ngValue] in each option.
You can even have a default null option and it works with Angular 12.
<select name="typeFather" [(ngModel)]="selectedType">
<option [ngValue]="null">Select a type</option>
<option *ngFor="let type of types" [ngValue]="type">{{type.title}}</option>
</select>
That approach is always going to work, however if you have a dynamic list, make sure you load it before the model.
You Can Select the Id using a Function
<option *ngFor="#c of countries" (change)="onchange(c.id)">{{c.name}}</option>
Create another getter for selected item
<form [formGroup]="countryForm">
<select formControlName="country">
<option *ngFor="let c of countries" [value]="c.id">{{c.name}}</option>
</select>
<p>Selected Country: {{selectedCountry?.name}}</p>
</form>
In ts :
get selectedCountry(){
let countryId = this.countryForm.controls.country.value;
let selected = this.countries.find(c=> c.id == countryId);
return selected;
}
Also, if nothing else from given solutions doesn't work, check if you imported "FormsModule" inside of "AppModule", that was a key for me.
You can get selected value also with help of click() by passing the selected value through the function
<md-select placeholder="Select Categorie"
name="Select Categorie" >
<md-option *ngFor="let list of categ" [value]="list.value" (click)="sub_cat(list.category_id)" >
{{ list.category }}
</md-option>
</md-select>
use this way also..
<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="let c of countries" value="{{c.id}}">{{c.name}}</option>
</select>
Attention Angular 2+ users:
for some reason, [value] does not work on elements. use [ngModel] instead.
<select [ngModel]="selectedCountry">
<option *ngFor="let country of countries" [value]="country">{{country.name}}</option>
</select>
Tested on Angular 11. I need an extra object 'typeSelected'. Pay attention I'm not using [(ngValue)] as other answers do:
<mat-select formControlName="type" [(value)]="typeSelected"
[compareWith]="typeComparation">
<mat-option *ngFor="let myType of allSurveysTypes" [value]="myType">
{{myType.title}}
</mat-option>
</mat-select>
//Declaration.
typeSelected: SurveyType;
...
//Assigning variable 'type' of object 'survey' to 'typeSelected'.
this.typeSelected = survey?.type;
...
//Function to compare SurveyType objects.
typeComparation = ( option, value ) => {
if (option && value) {
return option.id === value.id;
}
}
This code is very simple:
<select class="form-control" id="marasemaat" [(ngModel)]="fullNamePresentor"
[formControl]="stateControl" (change)="onSelect($event.target.value)">
<option *ngFor="let char of programInfo1;let i = index;"
onclick="currentSlide(9,false)"
value={{char.id}}>{{char.title + " "}} ----> {{char.name + " "+ char.family }} ---- > {{(char.time.split('T', 2)[1]).split(':',2)}}</option>
</select>

Angular 2 Dropdown Options Default Value

In Angular 1 I could select the default option for a drop down box using the following:
<select
data-ng-model="carSelection"
data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>
In Angular 2 I have:
<select class="form-control" [(ngModel)]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
<option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
How could I select a default option given my option data is:
[{name: 'arm'}, {name: 'back'}, {name:'leg'}] and my value I to default on on is back?
Add a binding to the selected property, like this:
<option *ngFor="#workout of workouts"
[selected]="workout.name == 'back'">{{workout.name}}</option>
If you assign the default value to selectedWorkout and use [ngValue] (which allows to use objects as value - otherwise only string is supported) then it should just do what you want:
<select class="form-control" name="sel"
[(ngModel)]="selectedWorkout"
(ngModelChange)="updateWorkout($event)">
<option *ngFor="let workout of workouts" [ngValue]="workout">
{{workout.name}}
</option>
</select>
Ensure that the value you assign to selectedWorkout is the same instance than the one used in workouts. Another object instance even with the same properties and values won't be recognized. Only object identity is checked.
update
Angular added support for compareWith, that makes it easier to set the default value when [ngValue] is used (for object values)
From the docs https://angular.io/api/forms/SelectControlValueAccessor
<select [compareWith]="compareFn" [(ngModel)]="selectedCountries">
<option *ngFor="let country of countries" [ngValue]="country">
{{country.name}}
</option>
</select>
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
This way a different (new) object instance can be set as default value and compareFn is used to figure out if they should be considered equal (for example if the id property is the same.
Add this Code at o position of the select list.
<option [ngValue]="undefined" selected>Select</option>
just set the value of the model to the default you want like this:
selectedWorkout = 'back'
I created a fork of #Douglas' plnkr here to demonstrate the various ways to get the desired behavior in angular2.
You Can approach this way:
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>
or this way:
<option *ngFor="let workout of workouts" [attr.value]="workout.name" [attr.selected]="workout.name == 'leg' ? true : null">{{workout.name}}</option>
or you can set default value this way:
<option [value]="null">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>
or
<option [value]="0">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>
Use index to show the first value as default
<option *ngFor="let workout of workouts; #i = index" [selected]="i == 0">{{workout.name}}</option>
According to https://angular.io/api/forms/SelectControlValueAccessor you
just need the following:
theView.html:
<select [compareWith]="compareFn" [(ngModel)]="selectedCountries">
<option *ngFor="let country of countries" [ngValue]="country">
{{country.name}}
</option>
</select>
theComponent.ts
import { SelectControlValueAccessor } from '#angular/forms';
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
Struggled a bit with this one, but ended up with the following solution... maybe it will help someone.
HTML template:
<select (change)="onValueChanged($event.target)">
<option *ngFor="let option of uifOptions" [value]="option.value" [selected]="option == uifSelected ? true : false">{{option.text}}</option>
</select>
Component:
import { Component, Input, Output, EventEmitter, OnInit } from '#angular/core';
export class UifDropdownComponent implements OnInit {
#Input() uifOptions: {value: string, text: string}[];
#Input() uifSelectedValue: string = '';
#Output() uifSelectedValueChange:EventEmitter<string> = new EventEmitter<string>();
uifSelected: {value: string, text: string} = {'value':'', 'text':''};
constructor() { }
onValueChanged(target: HTMLSelectElement):void {
this.uifSelectedValue = target.value;
this.uifSelectedValueChange.emit(this.uifSelectedValue);
}
ngOnInit() {
this.uifSelected = this.uifOptions.filter(o => o.value ==
this.uifSelectedValue)[0];
}
}
Fully fleshing out other posts, here is what works in Angular2 quickstart,
To set the DOM default: along with *ngFor, use a conditional statement in the <option>'s selected attribute.
To set the Control's default: use its constructor argument. Otherwise before an onchange when the user re-selects an option, which sets the control's value with the selected option's value attribute, the control value will be null.
script:
import {ControlGroup,Control} from '#angular/common';
...
export class MyComponent{
myForm: ControlGroup;
myArray: Array<Object> = [obj1,obj2,obj3];
myDefault: Object = myArray[1]; //or obj2
ngOnInit(){ //override
this.myForm = new ControlGroup({'myDropdown': new Control(this.myDefault)});
}
myOnSubmit(){
console.log(this.myForm.value.myDropdown); //returns the control's value
}
}
markup:
<form [ngFormModel]="myForm" (ngSubmit)="myOnSubmit()">
<select ngControl="myDropdown">
<option *ngFor="let eachObj of myArray" selected="eachObj==={{myDefault}}"
value="{{eachObj}}">{{eachObj.myText}}</option>
</select>
<br>
<button type="submit">Save</button>
</form>
You can Use that [ngModel] instead of [(ngModel)]and it is Ok
<select class="form-control" **[ngModel]="selectedWorkout"** (ngModelChange)="updateWorkout($event)">
<option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
You can do as above:
<select class="form-control"
[(ngModel)]="selectedWorkout"
(ngModelChange)="updateWorkout($event)">
<option *ngFor="#workout of workouts;
let itemIndex = index"
[attr.selected]="itemIndex == 0">
{{workout.name}}
</option>
</select>
In above code as you can see, selected attribute of the repeating option is set on checking index of the repeating loop of list. [attr.< html attribute name >] is used for setting html attribute in angular2.
Another approach will be setting model value in typescript file as :
this.selectedWorkout = this.workouts.length > 0
? this.workouts[0].name
: 'No data found';//'arm'
Add on to #Matthijs 's answer, please make sure your select element has a name attribute and its name is unique in your html template. Angular 2 is using input name to update changes. Thus, if there are duplicated names or there is no name attached to input element, the binding will fail.
I faced the same problem while using angular 11. But finally found a solution.
<option disabled selected value="undefined">Select an Option</option>
complete example with ngFor.
<select name="types" id="types" [(ngModel)]="model.type" #type="ngModel">
<option class="" disabled selected value="undefined">Select an Option</option>
<option *ngFor="let item of course_types; let x = index" [ngValue]="type.id">
{{ item.name }} </option>
</select>
Add binding property selected, but make sure to make it null, for other fields e.g:
<option *ngFor="#workout of workouts" [selected]="workout.name =='back' ? true: null">{{workout.name}}</option>
Now it will work
<select class="form-control" name='someting' [ngModel]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
<option value="{{workout.name}}" *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
If you are using form there should be name field inside select tag.
All you need to do is just add value to the option tag.
selectedWorkout value should be "back" , and its done.
If you don't want the 2-way binding via [(ngModel)], do this:
<select (change)="selectedAccountName = $event.target.value">
<option *ngFor="let acct of accountsList" [ngValue]="acct">{{ acct.name }}</option>
</select>
Just tested on my project on Angular 4 and it works! The accountsList is an array of Account objects in which name is a property of Account.
Interesting observation:
[ngValue]="acct" exerts the same result as [ngValue]="acct.name".
Don't know how Angular 4 accomplish it!
Step: 1 Create Properties declare class
export class Task {
title: string;
priority: Array<any>;
comment: string;
constructor() {
this.title = '';
this.priority = [];
this.comment = '';
}
}
Stem: 2 Your Component Class
import { Task } from './task';
export class TaskComponent implements OnInit {
priorityList: Array<any> = [
{ value: 0, label: '✪' },
{ value: 1, label: '★' },
{ value: 2, label: '★★' },
{ value: 3, label: '★★★' },
{ value: 4, label: '★★★★' },
{ value: 5, label: '★★★★★' }
];
taskModel: Task = new Task();
constructor(private taskService: TaskService) { }
ngOnInit() {
this.taskModel.priority = [3]; // index number
}
}
Step: 3 View File .html
<select class="form-control" name="priority" [(ngModel)]="taskModel.priority" required>
<option *ngFor="let list of priorityList" [value]="list.value">
{{list.label}}
</option>
</select>
Output:
You just need to put the ngModel and the value you want selected:
<select id="typeUser" ngModel="Advanced" name="typeUser">
<option>Basic</option>
<option>Advanced</option>
<option>Pro</option>
</select>
For me, I define some properties:
disabledFirstOption = true;
get isIEOrEdge(): boolean {
return /msie\s|trident\/|edge\//i.test(window.navigator.userAgent)
}
Then in the constructor and ngOnInit
constructor() {
this.disabledFirstOption = false;
}
ngOnInit() {
setTimeout(() => {
this.disabledFirstOption = true;
});
}
And in the template I add this as the first option inside the select element
<option *ngIf="isIEOrEdge" [value]="undefined" [disabled]="disabledFirstOption" selected></option>
If you allow to select the first option you can just remove the usage of the property disabledFirstOption
In my case, here this.selectedtestSubmitResultView is set with default value based on conditions and an variable testSubmitResultView must be one and same as testSubmitResultView. This indeed worked for me
<select class="form-control" name="testSubmitResultView" [(ngModel)]="selectedtestSubmitResultView" (ngModelChange)="updatetestSubmitResultView($event)">
<option *ngFor="let testSubmitResultView of testSubmitResultViewArry" [ngValue]="testSubmitResultView" >
{{testSubmitResultView.testSubmitResultViewName}}
</option>
</select>
For More Information,
testSubmitResultViewArry: Array<any> = [];
selectedtestSubmitResultView: string;
getTestSubmitResultViewList() {
try {
this.examService.getTestSubmitResultViewDetails().subscribe(response => {
if (response != null && response !== undefined && response.length > 0) {
response.forEach(x => {
if (x.isDeleted === false) {
this.testSubmitResultViewArry.push(x);
}
if (x.isDefault === true) {
this.selectedtestSubmitResultView = x;
}
})
}
});
} catch (ex) {
console.log('Method: getTestSubmitResultViewList' + ex.message);
}
}
I faced this Issue before and I fixed it with vary simple workaround way
For your Component.html
<select class="form-control" ngValue="op1" (change)="gotit($event.target.value)">
<option *ngFor="let workout of workouts" value="{{workout.name}}" name="op1" >{{workout.name}}</option>
</select>
Then in your component.ts you can detect the selected option by
gotit(name:string) {
//Use it from hare
console.log(name);
}
works great as seen below:
<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
[class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)"
[class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
<option value="">Selecione um tipo</option>
<option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
</select>