使用 Angular 在下拉列表中选择的设置
Setting selected in dropdownlist with Angular
我在下拉列表中显示了一个列表,但它默认显示为空白而不是下拉列表中的第一项。
我尝试添加 let i = 0
,然后添加 [selected]="i = 0"
,但这似乎没有将默认项设置为第一项,但是我从 [=15= 收到正确的值].
下面是我的代码:
<div class="form-group">
<label for="userName">User Name</label>
<select formControlName="userName" class="form-control" (change)="userChange($event)">
<option *ngFor="let row of usersModel;let i = index" value="{{ row.id }}" [selected]="i == 0">{{ row.userName }} {{ i }}</option>
</select>
</div>
这是我的 TypeScript 文件:
import { Component, OnInit } from '@angular/core';
import { UserAdminService } from '../../services/user-admin.service';
import { FormBuilder, Form, FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'lib-add-user-to-role',
templateUrl: './add-user-to-role.component.html',
styleUrls: ['./add-user-to-role.component.css']
})
export class AddUserToRoleComponent implements OnInit {
addUserToRoleForm: FormGroup;
rolesModel: any[];
usersModel: any[];
selectedRole: string;
selectedUser: string;
constructor(private userAdminService: UserAdminService, private formBuilder: FormBuilder, private router: Router) {
var roleControl = new FormControl('');
var userControl = new FormControl('');
this.addUserToRoleForm = formBuilder.group({ roleName: roleControl, userName: userControl });
}
ngOnInit() {
this.userAdminService.getRoles().subscribe(roles => {
this.rolesModel = roles;
this.selectedRole = this.rolesModel[0].name;
this.userAdminService.getUsersNotInRole(this.selectedRole).subscribe(users => {
this.usersModel = users;
this.selectedUser = this.usersModel[0].id;
console.log(this.usersModel[0].userName);
this.addUserToRoleForm.controls['roleName'].setValue(this.rolesModel[0].name);
this.addUserToRoleForm.controls['userName'].setValue(this.usersModel[0].userName);
});
});
}
userChange(event: any) {
this.selectedUser = event.target.value;
console.log('Selected ' + this.selectedUser);
}
AddUserToRole() {
this.userAdminService.addUserToRole(this.selectedUser, this.selectedRole)
.subscribe(result => {
if (result.success) {
this.router.navigate(['/roleusermaint']);
}
else {
console.log('Error Received on adding user to role');
}
});
}
}
如您所见,我在文本中添加了 {{ i }}
以确保它显示 i
的值,并且确实如此:
我错过了什么?
感谢您的帮助!
@Axle,如果您使用的是响应式表单,则无需使用 [selected]
或 (change)
,只需在创建表单时为 userName[=15= 赋值]
使用构造函数
const firstId=usersModel[0].id
this.form=new FormGroup({
userName:new FormControl(firstId)
})
使用表单生成器
const firstId=usersModel[0].id
this.form=this.fb.group({
userName:firstId
})
在创建表单后使用 setValue
const firstId=usersModel[0].id
this.form.get('userName').setValue(firstId)
当您使用 Angular 反应形式时,请尽量将逻辑保留在 ts
文件本身中。
使用setValue(),您可以为控件设置默认值。
要设置默认值以形成控件,您可以这样设置,
this.form.controls['country'].setValue(this.countries[0].id)
在模板中使用它,
<option *ngFor="let country of countries" [value]="country.id">
{{ country.name }}
</option>
参考:
完整的示例代码类似于,
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import {Country} from './country';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
countries = [
{
id: 'us',
name: 'United States'
},
{
id: 'uk',
name: 'United Kingdom'
},
{
id: 'ca',
name: 'Canada'
}
];
form: FormGroup;
ngOnInit(){
this.form = new FormGroup({
country: new FormControl('')
});
this.form.controls['country'].setValue(this.countries[0].id)
}
}
app.component.html
<form [formGroup]="form">
<select formControlName="country">
<option *ngFor="let country of countries" [value]="country.id">
{{ country.name }}
</option>
</select>
</form>
我在下拉列表中显示了一个列表,但它默认显示为空白而不是下拉列表中的第一项。
我尝试添加 let i = 0
,然后添加 [selected]="i = 0"
,但这似乎没有将默认项设置为第一项,但是我从 [=15= 收到正确的值].
下面是我的代码:
<div class="form-group">
<label for="userName">User Name</label>
<select formControlName="userName" class="form-control" (change)="userChange($event)">
<option *ngFor="let row of usersModel;let i = index" value="{{ row.id }}" [selected]="i == 0">{{ row.userName }} {{ i }}</option>
</select>
</div>
这是我的 TypeScript 文件:
import { Component, OnInit } from '@angular/core';
import { UserAdminService } from '../../services/user-admin.service';
import { FormBuilder, Form, FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'lib-add-user-to-role',
templateUrl: './add-user-to-role.component.html',
styleUrls: ['./add-user-to-role.component.css']
})
export class AddUserToRoleComponent implements OnInit {
addUserToRoleForm: FormGroup;
rolesModel: any[];
usersModel: any[];
selectedRole: string;
selectedUser: string;
constructor(private userAdminService: UserAdminService, private formBuilder: FormBuilder, private router: Router) {
var roleControl = new FormControl('');
var userControl = new FormControl('');
this.addUserToRoleForm = formBuilder.group({ roleName: roleControl, userName: userControl });
}
ngOnInit() {
this.userAdminService.getRoles().subscribe(roles => {
this.rolesModel = roles;
this.selectedRole = this.rolesModel[0].name;
this.userAdminService.getUsersNotInRole(this.selectedRole).subscribe(users => {
this.usersModel = users;
this.selectedUser = this.usersModel[0].id;
console.log(this.usersModel[0].userName);
this.addUserToRoleForm.controls['roleName'].setValue(this.rolesModel[0].name);
this.addUserToRoleForm.controls['userName'].setValue(this.usersModel[0].userName);
});
});
}
userChange(event: any) {
this.selectedUser = event.target.value;
console.log('Selected ' + this.selectedUser);
}
AddUserToRole() {
this.userAdminService.addUserToRole(this.selectedUser, this.selectedRole)
.subscribe(result => {
if (result.success) {
this.router.navigate(['/roleusermaint']);
}
else {
console.log('Error Received on adding user to role');
}
});
}
}
如您所见,我在文本中添加了 {{ i }}
以确保它显示 i
的值,并且确实如此:
我错过了什么?
感谢您的帮助!
@Axle,如果您使用的是响应式表单,则无需使用 [selected]
或 (change)
,只需在创建表单时为 userName[=15= 赋值]
使用构造函数
const firstId=usersModel[0].id
this.form=new FormGroup({
userName:new FormControl(firstId)
})
使用表单生成器
const firstId=usersModel[0].id
this.form=this.fb.group({
userName:firstId
})
在创建表单后使用 setValue
const firstId=usersModel[0].id
this.form.get('userName').setValue(firstId)
当您使用 Angular 反应形式时,请尽量将逻辑保留在 ts
文件本身中。
使用setValue(),您可以为控件设置默认值。
要设置默认值以形成控件,您可以这样设置,
this.form.controls['country'].setValue(this.countries[0].id)
在模板中使用它,
<option *ngFor="let country of countries" [value]="country.id">
{{ country.name }}
</option>
参考:
完整的示例代码类似于,
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import {Country} from './country';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
countries = [
{
id: 'us',
name: 'United States'
},
{
id: 'uk',
name: 'United Kingdom'
},
{
id: 'ca',
name: 'Canada'
}
];
form: FormGroup;
ngOnInit(){
this.form = new FormGroup({
country: new FormControl('')
});
this.form.controls['country'].setValue(this.countries[0].id)
}
}
app.component.html
<form [formGroup]="form">
<select formControlName="country">
<option *ngFor="let country of countries" [value]="country.id">
{{ country.name }}
</option>
</select>
</form>