或者,您可以使用 ng [ngValue]。
当您绑定到[value] 时,它通常采用字符串或数字的格式。
但是,在某些情况下,您可能希望将整个对象绑定到您的选择选项。这时候 ngValue 就派上用场了。
在本例中,我们将整个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 的局部变量中。如果未选择 select 上的任何选项,带有 *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。