我有两个组件,一个是员工,另一个是部门。我想制作一个下拉列表,以便员工可以选择部门。
我实现了一种方法,用于获取员工组件中的所有部门:
getAllDepartment(){
this._employeeService.getAllDepartment()
.subscribe(data => this.departments = data.json());
}
在我的员工html选择中看起来像这样:
<label for="editTitle">Department:</label><br>
<select [(ngModel)]="newItem.Department" (click)="getAll()" style="width: 180px">
<option *ngFor="#department of departments" [value]="department.departmentNo">{{department.departmentName}}</option>
</select>
但是注意到了 使此下拉列表工作和选择项目的最佳方法是什么? 这是啊我选择的地方:
<form #f="ngForm" [hidden]="!showAddView" align="center">
<div>
<label for="editTitle">Employee No:</label><br>
<input type="text" [(ngModel)]="newItem.employeeNo" ngControl="employeeNo" required >
</div>
<div>
<label for="editAbrv">Employee name:</label><br>
<input type="text" [(ngModel)]="newItem.employeeName" ngControl="demployeeName" required >
</div>
<div>
<label for="editTitle">Department:</label><br>
<select [(ngModel)]="newItem.departmentNo" (click)="getAll()" style="width: 180px">
<option *ngFor="#department of departments" [value]="department.departmentNo">{{department.departmentName}}</option>
</select>
</div>
<div>
<label for="editAbrv">Salary:</label><br>
<input type="text" [(ngModel)]="newItem.salary" ngControl="salary" required>
</div>
<div>
<a href="javascript:void(0);" (click)="addEmployee(newItem)" title="Add">
Save
</a>
<a href="javascript:void(0);" (click)="showHide($event)" >
Cancel
</a>
</div>
</form>
答案 0 :(得分:1)
您将选择框的click事件绑定到getAll()
方法,但您定义的方法称为getAllDepartment()
。
您需要将事件绑定到现有方法名称。
话虽这么说,但我不确定为什么每次点击下拉列表时都想重新加载部门。如果所需的行为是在初始化组件时加载部门一次,则应该向组件添加constructor()
方法,该方法将自动调用。
constructor() {
this._employeeService.getAllDepartment()
.subscribe(data => this.departments = data.json());
}