在 Angular7 的选择列表中设置最初选定的项目
我是 Angular 框架的初学者。我想设置按值选择下拉菜单的默认值。 .ts 文件中应该添加什么才能得到预期的结果?
.html 文件:
<select name="employees" (change) = "onEdit(emp)" [(ngModel)]="employees" class="form-control">
<option *ngFor="let emp of employees" [value]="emp.id">
{{emp.fullName}}
</option>
</select>
.ts 文件:
ngOnInit() {
this.service.getEmployeenames().subscribe(actionArray => {
this.employees = actionArray.map(item => {
return {
id: item.payload.doc.id,
...item.payload.doc.data()
} as Employee;
})
});
}
假设下拉列表中有 3 项选择:
Employee1
Employee2
Employee3
默认我想设置为Employee1
。
谢谢!
最佳答案
或者,您可以使用 ng [ngValue]
.
当您绑定(bind)到[value]
时,通常采用字符串或数字的格式。
但是,在某些情况下您可能希望将整个对象绑定(bind)到您的选择选项。这就是 ngValue 派上用场的时候。
对于这个例子,我们绑定(bind)了整个 emp
反对选项值。我们选择了employee
的第一个索引数组作为默认选定值。
在 component.ts 上,
employee: any = undefined;
employees = [
{fullName: 'Employee-0',id:"0"},
{fullName: 'Employee-1',id:"1"},
{fullName: 'Employee-2',id:"2"}
];
constructor() {
this.employee = this.employees[1];
console.log(this.employee)
}
组件.html,
<select name="employees" (change) = "onEdit(emp)" [(ngModel)]="employee" class="form-control">
<option *ngFor="let emp of employees" [ngValue]="emp">
{{emp.fullName}}
</option>
</select>
我创建了一个demo在这里。
编辑:为了在代码上添加所需的验证,您需要在 <select>
上添加必需的属性。标签。我还在选择上添加了默认占位符。
<select name="employeeInput" [(ngModel)]="employee" required class="form-control" #employeeInput="ngModel" >
<option disabled [ngValue]="null">--Selected--</option>
<option *ngFor="let emp of employees" [ngValue]="emp">
{{emp.fullName}}
</option>
</select>
<div *ngIf="employeeInput.control.errors?.required && isSubmitted">
Name is required.
</div>
<div>
<button (click)="submit()">SUBMIT</button>
</div>
#employeeInput="ngModel"
导出NgModel
到一个名为employeeInput 的局部变量中。如果选择上没有选择任何选项,带有 *ngIf 的将显示验证错误消息。
在你的 component.ts 上,我设置了 employee
如null
以便选择默认占位符。此外,submit()
方法集isSubmitted
设置为 true 以便验证消息仅在提交表单时显示。 if 条件将检查是否使用值选择了输入,因此条件为 this.employeeInput.errors
.
@ViewChild('employeeInput') employeeInput: TemplateRef<any>;
employee: any = undefined;
isSubmitted: boolean = false;
employees = [
{fullName: 'Employee-0',id:"0"},
{fullName: 'Employee-1',id:"1"},
{fullName: 'Employee-2',id:"2"}
];
constructor() {
this.employee = null;
}
submit() {
this.isSubmitted = true;
if (!this.employeeInput.errors) {
// will only enter this block of code if the select has no errors
// insert the rest of your firebase code
}
查看 demo .
关于angular - 在 Angular7 的选择列表中设置最初选定的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55428353/