我需要在Angular 2中更新我的模型。
我的更新方法看起来:
putDep(item) {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.selected.departmentName = item.departmentName;
this.selected.departmentLocation = item.departmentLocation;
return this.http.put('http://localhost:65402/company/api/department'+ "/update/" + this.selected.departmentNo, JSON.stringify(item),{headers: headers})
.subscribe(res => {this.departments = res.json();});
}
和HTML代码:
<form #selected="ngForm" [hidden]="!showEditView" align="center">
<div>
<label for="editAbrv">Department No:</label><br>
<input ngControl="departmentNo" placeholder="name">
</div>
<div>
<label for="editAbrv">Department name:</label><br>
<input ngControl="departmentName" placeholder="name">
</div>
<div>
<label for="editAbrv">Department Location:</label><br>
<input ngControl="departmentLocation" placeholder="location">
</div>
<div>
<a href="javascript:void(0);" (click)="putDep(selected.value)" title="Add">
Save
</a>
<a href="javascript:void(0);" (click)=showHide($event) >
Cancel
</a>
</div>
</form>
问题在于与模型的双向绑定。这是它在后端的外观:
[HttpPut]
[Route("Update/{id}")]
public async Task<HttpResponseMessage> Update(int id, DepartmentModel model)
问题在于,当我点击编辑模型时,我的int id传递给后端,但我的模型id(应该与传递的id相同)为null。此外,当我点击编辑按钮时,我无法看到当我输入模型值时视图的变化。在角度1我解决它很快,但在Angular 2是斗争。关键是当我点击编辑时我希望id自动与我的模型连接,并且我可以在输入字段(以及其他2个属性)中看到它。谢谢你的帮助!
答案 0 :(得分:1)
我会使用ngModel
来解决这个问题。选择元素时,您可以在组件中设置属性selectedDepartment
,并更新部门。您可以在输入上绑定此对象的属性(仅限您要更新的属性)。
此selectedDepartment
对象包含当前标识符中包含的所有属性。
点击&#34;保存&#34;按钮,您可以发送此对象而不是表单值。这样你就不会丢失标识符。
以下是表单的代码:
<form #selected="ngForm" [hidden]="!showEditView" align="center">
<div>
<label for="editAbrv">Department No:</label><br>
<input [(ngForm)]="selectedDepartment.departmentNo" ngControl="departmentNo" placeholder="name">
</div>
<div>
<label for="editAbrv">Department name:</label><br>
<input [(ngForm)]="selectedDepartment.departmentName" ngControl="departmentName" placeholder="name">
</div>
<div>
<label for="editAbrv">Department Location:</label><br>
<input [(ngForm)]="selectedDepartment.departmentLocation" ngControl="departmentLocation" placeholder="location">
</div>
<div>
<a href="javascript:void(0);" (click)="putDep(selectedDepartment)" title="Add">
Save
</a>
<a href="javascript:void(0);" (click)=showHide($event) >
Cancel
</a>
</div>
</form>