Html Angular 2 下拉选项默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35978450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 Dropdown Options Default Value
提问by ClickThisNick
In Angular 1 I could select the default option for a drop down box using the following:
在 Angular 1 中,我可以使用以下命令为下拉框选择默认选项:
<select
data-ng-model="carSelection"
data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>
In Angular 2 I have:
在 Angular 2 中,我有:
<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
?
[{name: 'arm'}, {name: 'back'}, {name:'leg'}]
我默认的值是back
?
回答by Douglas
Add a binding to the selected
property, like this:
向selected
属性添加绑定,如下所示:
<option *ngFor="#workout of workouts"
[selected]="workout.name == 'back'">{{workout.name}}</option>
回答by Günter Z?chbauer
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:
如果您将默认值分配给selectedWorkout
并使用[ngValue]
(允许将对象用作值 - 否则仅支持字符串),那么它应该只做您想做的事情:
<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.
确保您分配给的值与 中使用的值selectedWorkout
相同workouts
。即使具有相同属性和值的另一个对象实例也不会被识别。只检查对象身份。
update
更新
Angular added support for compareWith
, that makes it easier to set the default value when [ngValue]
is used (for object values)
Angular 添加了对 的支持compareWith
,这使得在使用时更容易设置默认值[ngValue]
(用于对象值)
From the docs https://angular.io/api/forms/SelectControlValueAccessor
从文档https://angular.io/api/forms/SelectControlValueAccessor
<select [compareWith]="compareFn" [(ngModel)]="selectedCountries"> <option *ngFor="let country of countries" [ngValue]="country"> {{country.name}} </option> </select>
<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; }
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.
通过这种方式,可以将不同的(新)对象实例设置为默认值,compareFn
并用于确定它们是否应该被视为相等(例如,id
属性是否相同。
回答by Matthijs
回答by Mahesh
Add this Code at o position of the select list.
将此代码添加到选择列表的 o 位置。
<option [ngValue]="undefined" selected>Select</option>
<option [ngValue]="undefined" selected>Select</option>
回答by Anil Samal
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>
回答by Sajith Mantharath
Use index to show the first value as default
使用 index 将第一个值显示为默认值
<option *ngFor="let workout of workouts; #i = index" [selected]="i == 0">{{workout.name}}</option>
回答by azatprog
According to https://angular.io/api/forms/SelectControlValueAccessoryou just need the following:
根据https://angular.io/api/forms/SelectControlValueAccessor您只需要以下内容:
theView.html:
视图.html:
<select [compareWith]="compareFn" [(ngModel)]="selectedCountries">
<option *ngFor="let country of countries" [ngValue]="country">
{{country.name}}
</option>
</select>
theComponent.ts
组件.ts
import { SelectControlValueAccessor } from '@angular/forms';
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
回答by johnb
Struggled a bit with this one, but ended up with the following solution... maybe it will help someone.
对这个有点挣扎,但最终得到了以下解决方案......也许它会帮助某人。
HTML template:
HTML模板:
<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];
}
}
回答by Pranav Labhe
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.
如您所见,在上面的代码中,重复选项的 selected 属性设置在检查列表重复循环的索引上。[attr.<html 属性名称>] 用于设置angular2中的html属性。
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'
回答by BeatriceThalo
Fully fleshing out other posts, here is what works in Angular2 quickstart,
充分充实其他帖子,这是 Angular2 快速入门中的工作原理,
To set the DOM default: along with *ngFor
, use a conditional statement in the <option>
's selected
attribute.
要设置 DOM 默认值:与 一起*ngFor
,在<option>
的selected
属性中使用条件语句。
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.
要设置Control
的默认值:使用其构造函数参数。否则,当用户重新选择一个选项时,在 onchange 之前,使用所选选项的 value 属性设置控件的值,控件值将为空。
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>