Angular 2下拉选项默认值

在Angular 1中,我可以使用以下选项来select下拉框的默认选项:

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

在Angular 2中我有:

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

我怎样才能select一个默认的选项给我的选项数据是:

[{name: 'arm'}, {name: 'back'}, {name:'leg'}]和我默认的值是back

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

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

只需将模型的值设置为您想要的默认值即可:

 selectedWorkout = 'back' 

我在这里创build了@Douglas'plnkr的分支来演示在angular2中获得所需行为的各种方法。

如果将默认值赋给selectedWorkout并使用[ngValue] (允许使用对象作为值 – 否则只支持string),那么它应该做你想做的事情:

 <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使用的值相同。 另一个对象实例即使具有相同的属性和值也不会被识别。 只有对象身份被检查。

更新

Angular增加了对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; } 

这样一个不同的(新)对象实例可以被设置为默认值,并且compareFn被用来判断它们是否应该被认为是相等的(例如,如果id属性是相同的。

你可以这样做

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

或者你可以这样设置deafult vlaue

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

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

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

将此代码添加到select列表的o位置。

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

你可以像上面那样做:

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

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

另一种方法是将typecript文件中的模型值设置为:

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

你可以使用[ngModel]而不是[(ngModel)] ,它是好的

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

用这个方法挣扎了一下,但最终得到了下面的解决scheme…也许它会帮助别人。

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

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

要设置DOM默认值:和*ngFor ,在<option>selected属性中使用条件语句。

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

脚本:

 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> 

添加绑定属性select,但确保使其为空,其他领域例如:

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

现在它会工作

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

 <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字段。

所有你需要做的只是增加valueoption标签。

selectedWorkout值应该是“后退”,并完成。

之前我遇到过这个问题,我用各种简单的解决方法修复了这个问题

对于你的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> 

然后在你的component.ts中,你可以通过检测select的选项

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

如果您不想通过[(ngModel)]进行双向绑定,请执行以下操作:

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

刚在我的Angular 4项目上testing过,效果很好! accountsList是一个Account对象的数组,其中Name是Account的一个属性。

有趣的观察:
[ngValue] =“acct”与[ngValue] =“acct.name”的效果相同。
不知道Angular 4是如何实现的!

步骤:1创build属性声明类

 export class Task { title: string; priority: Array<any>; comment: string; constructor() { this.title = ''; this.priority = []; this.comment = ''; } } 

词干:2你的组件类

 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> 

输出:

在这里输入图像描述

开始玩AngularJS 4和Typescript,这是具有挑战性的。 我正在使用Angular Reactive Forms(或模型驱动的表单),并且有一个Address组件,其中包含国家/地区字段,我想用默认值作为下拉列表。 我跟着下面

  1. 创buildaddress.ts模型(地址)
  2. 创buildaddress.component.ts (AddressComponent)
  3. 创buildaddress.component.html (模板)
  4. 导入AddressComponent到你的模块(如路由器,如果你有)

型号address.ts如下


 export class Address { type: string; street: string; city: string; postalcode: string; provinces = ['AB', 'BC', 'MB', 'NB', 'NL', 'NS', 'NT', 'NU', 'ON', 'PE', 'QC', 'SK', 'YT']; countries = ['Canada', 'USA']; } 

之后是address.component.ts


 import { Component, Input, OnInit } from '@angular/core'; import { FormArray, FormGroup, FormBuilder, Validators } from '@angular/forms'; import { Address } from '../../models/address'; @Component({ selector: 'address', templateUrl: './address.component.html' }) export class AddressComponent implements OnInit { @Input() addressForm: FormGroup; address = new Address(); constructor (private fb: FormBuilder){} ngOnInit(){ this.addressForm = this.fb.group({ type: ['', Validators.required], street: [''], city: ['', Validators.required], postalcode: [''], provinces: [this.address.provinces], countries: [this.address.countries] }); } } 

随后是address.component.html


 <form [formGroup]="addressForm" class="address"> <div class="form-group"> <label>Address type</label> <input type="text" class="form-control" formControlName="type"> </div> <div class="form-group"> <label>Street</label> <input type="text" class="form-control" formControlName="street"> </div> <div class="form-group"> <label>City</label> <input type="text" class="form-control" formControlName="city"> </div> <div class="form-group"> <label>Postal code</label> <input type="text" class="form-control" (formControlName)="postalcode"> </div> <div class="form-group"> <label>Province</label> <select class="form-control" formControlName="provinces"> <option *ngFor="let province of address.provinces" [value]="province"> {{province}} </option> </select> </div> <div class="form-group"> <label>country</label> <select class="form-control" formControlName="countries"> <option *ngFor="let country of address.countries" [value]="country"> {{country}} </option> </select> </div> </form> 

通过以上三个步骤,我可以按照以下步骤自行提交地址

  1. 更新我有自定义路由的app-routing.module.ts
  2. 更新app.module.ts
  3. 更新app.component.ts以将地址包含在路由器出口标签中

更新app-routing.module.ts


 import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { UserRegistrationComponent } from '../user/user-registration.component'; //temporary import { AddressComponent } from '../address/address.component'; const routes : Routes = [ { path: 'user/register', component: UserRegistrationComponent }, { path: 'temp/address', component: AddressComponent } ] @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} 

紧接着app.module.ts导入AddressComponent,并将其包含在NgModule装饰器的声明数组中


 import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppRoutingModule } from './modules/app-routing.module' import { AppComponent } from './app.component'; import { UserService } from './services/user.service' import { UserRegistrationComponent } from './user/user-registration.component'; //import temporary import { AddressComponent } from './address/address.component'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule, HttpModule, AppRoutingModule ], declarations: [ AppComponent, UserRegistrationComponent, AddressComponent ], exports : [ ], providers: [ UserService ], bootstrap: [ AppComponent ] }) export class AppModule { } 

最后,更新app.component.ts html模板以包含Address组件的链接,以便我们可以导航到它并查看地址表单。


 import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <div class="container"> <h1>Sample</h1> <nav> <a routerLink="/user/register" routerLinkActive="active">Register User</a><br> <a routerLink="/temp/address" routerLinkActive="active">Address</a> </nav> <router-outlet></router-outlet> </div> `, }) export class AppComponent { name = 'Sample'; } 

就是这样。 呈现的地址表单如下所示:

在这里输入图像描述

现在我有一个地址反应forms的组件,我可以embedded任何地方我需要一个地址字段。 它只是为地址字段感到很多代码。 新的AngularJS 4和Typescript,所以代码可能会有错误。