角度2下拉选项默认值

在角度1中,我可以选择下拉框的默认选项,如下所示:

<select
data-ng-model="carSelection"
data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>

在角度2中,我有:

<select class="form-control" [(ngModel)]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
<option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>

根据我的选项数据,如何选择默认选项是:

我的缺省值是 back

295419 次浏览

selected属性添加绑定,如下所示:

<option *ngFor="#workout of workouts"
[selected]="workout.name == 'back'">\{\{workout.name}}</option>

只需将模型的值设置为默认值,如下所示:

selectedWorkout = 'back'

我创建了@Douglas 的 plnkr 给你分支来演示在 angular2中获得所需行为的各种方法。

充分充实其他职位,这里是什么工作在 Angular2快速启动,

要设置 DOM 默认值: 除了 *ngFor,还要在 <option>selected属性中使用一个 If判断语句。

要设置 Control的默认值: 使用它的构造函数参数。否则,当用户重新选择一个选项(该选项使用所选选项的 value 属性设置控件的值)时,在发生 onchange 之前,控件的值将为空。

剧本:

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
}
}

标价:

<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>

使用 index 将第一个值显示为默认值

<option *ngFor="let workout of workouts; #i = index" [selected]="i == 0">\{\{workout.name}}</option>

如果你将默认值赋给 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>

确保分配给 selectedWorkout的值与 workouts中使用的实例相同。另一个对象实例即使具有相同的属性和值也不会被识别。只检查对象标识。

更新

角度增加了对 compareWith的支持,这使得在使用 [ngValue]时(对于对象值)更容易设置默认值

来自 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 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>

现在会成功的

添加到@Matthijs 的回答中,请确保您的 select元素具有 name属性,并且它的 name在您的 html 模板中是唯一的。角度2使用输入名称来更新更改。因此,如果有重复的名称或没有名称附加到输入元素,绑定将失败。

你可以用那个 [ngModel]代替 [(ngModel)],这样就可以了

<select class="form-control" **[ngModel]="selectedWorkout"** (ngModelChange)="updateWorkout($event)">
<option *ngFor="#workout of workouts">\{\{workout.name}}</option>
</select>

你可以这样做:

<option *ngFor="let workout of workouts" [value]="workout.name">\{\{workout.name}}</option>

或者这样:

  <option *ngFor="let workout of workouts" [attr.value]="workout.name" [attr.selected]="workout.name == 'leg' ? true : null">\{\{workout.name}}</option>

或者你可以这样设置默认值:

<option [value]="null">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">\{\{workout.name}}</option>

或者

<option [value]="0">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">\{\{workout.name}}</option>
<select class="form-control" name='someting' [ngModel]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
<option value="\{\{workout.name}}" *ngFor="#workout of workouts">\{\{workout.name}}</option>
</select>

如果您使用的是表单,那么在 select标记中应该有 name字段。

您所需要做的就是将 value添加到 option标记中。

selectedWorkout值应该是“返回”的,并且它已经完成了。

在选择列表的 o 位置添加此代码。

<option [ngValue]="undefined" selected>Select</option>

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>

在上面的代码中,您可以看到,重复选项的选定属性设置在检查列表的重复循环的索引上。[俄语]。< html 属性名 > ]用于在 angular2中设置 html 属性。

另一种方法是在打印文件中将模型值设置为:

this.selectedWorkout = this.workouts.length > 0
? this.workouts[0].name
: 'No data found';//'arm'

I faced this Issue before and I fixed it with vary simple workaround way

对于您的组件.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>

然后,您可以通过以下方法检测选定的选项:

gotit(name:string) {
//Use it from hare
console.log(name);
}

虽然有点纠结,但最后还是找到了下面的解决办法... 也许能帮到别人。

HTML 模板:

<select (change)="onValueChanged($event.target)">
<option *ngFor="let option of uifOptions" [value]="option.value" [selected]="option == uifSelected ? true : false">\{\{option.text}}</option>
</select>

组成部分:

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];
}
}

如果您不希望通过[(ngModel)]进行双向绑定,可以这样做:

<select (change)="selectedAccountName = $event.target.value">
<option *ngFor="let acct of accountsList" [ngValue]="acct">\{\{ acct.name }}</option>
</select>

刚刚测试了我的项目在角度4和它的工程!AccountsList 是 Account 对象的数组,其中 name 是 Account 的属性。

有趣的观察:
[ ngValue ] = “ acct”施加与[ ngValue ] = “ acct.name”相同的结果。
不知道角度4是怎么做到的!

步骤: 1创建属性声明类

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
}
}

步骤: 3查看文件 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:

enter image description here

根据 https://angular.io/api/forms/SelectControlValueAccessor你 只需要以下几点:

返回文章页面观点:

<select [compareWith]="compareFn"  [(ngModel)]="selectedCountries">
<option *ngFor="let country of countries" [ngValue]="country">
\{\{country.name}}
</option>
</select>

组件

import { SelectControlValueAccessor } from '@angular/forms';
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}

作品如下:

<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>

您只需要输入 ngModel 和您想要选择的值:

<select id="typeUser" ngModel="Advanced" name="typeUser">
<option>Basic</option>
<option>Advanced</option>
<option>Pro</option>
</select>

对我来说,我定义了一些属性:

disabledFirstOption = true;


get isIEOrEdge(): boolean {
return /msie\s|trident\/|edge\//i.test(window.navigator.userAgent)
}

然后在构造函数和 ngOnInit 中

constructor() {
this.disabledFirstOption = false;
}


ngOnInit() {
setTimeout(() => {
this.disabledFirstOption = true;
});
}

在模板中,我将其添加为 select 元素中的第一个选项

<option *ngIf="isIEOrEdge" [value]="undefined" [disabled]="disabledFirstOption" selected></option>

如果允许选择第一个选项,那么只需删除 disabledFirstOption 属性的用法

在我的例子中,这里根据条件使用默认值设置 this.selectedtestSubmitResultView,并且变量 testSubmitResultView必须与 testSubmitResultView相同。这确实对我有用

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

我在使用角度11的时候也遇到了同样的问题,但是最终我找到了一个解决方案。

  <option disabled selected value="undefined">Select an Option</option>

使用 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>