我是编程方面的新手,需要一些建议。
我在我的数据库中创建了两个表 - 员工(使用外键" emp_depId ")和部门价值观(人力资源,技术,财务)。为了创建一个员工,我需要emp_depId,但是从我的表单中选择,我得到 depName 。我能做什么?我必须向服务器发送一个请求,并从数据绑定调用方法获取所有部门,并使用" depName"参数,它返回我必要的Id。比我将它分配给employee.emp_DepId并保存。
这是我的表格:
<form novalidate #form="ngForm" (ngSubmit)="submitForm(form)" (reset)="resetForm()" >
<div class="form-group">
<label>First Name</label>
<input class="form-control" name="firstName" [(ngModel)]="employee.firstName" required />
</div>
<div class="form-group">
<label>Last Name</label>
<input class="form-control" name="lastName" [(ngModel)]="employee.lastName" required />
</div>
<div class="form-group">
<label>Department</label>
<select class="form-control" name="depName" [(ngModel)]="getDepId(department.depName)">
<option *ngFor="let depName of getDepartments(); let i = index" [value] = "depName[i]">
{{depName}}
</option>
</select>
</div>
<button type="submit" class="btn btn-primary"
[class.btn-warning]="editing" [disabled]="form.invalid">
{{editing ? "Save" : "Create"}}
</button>
<button type="reset" class="btn btn-secondary" routerLink="/">Cancel</button>
</form>
我是对的吗?谢谢。
答案 0 :(得分:0)
根据您的代码,您可以这样做:
<select class="form-control" name="emp_DepId" [(ngModel)]="employee.emp_DepId">
<option *ngFor="let depName of getDepartments(); let i = index" [value] = "getDepId(depName)">
{{depName}}
</option>
</select>
但理想情况下应该是这样的:
// output of getDepartments() should look like this
[
{ id : 1 , name : 'department 1'},
{ id : 2 , name : 'department 2'}
{ id : 3 , name : 'department 3'}
]
<select class="form-control" name="emp_DepId" [(ngModel)]="employee.emp_DepId">
<option *ngFor="let dep of getDepartments(); let i = index" [value] = "dep.id">
{{dep.name}}
</option>
</select>