gpt4 book ai didi

angularjs - 更新模型时 Angular 2 中的双向绑定(bind)

转载 作者:可可西里 更新时间:2023-11-01 17:34:32 25 4
gpt4 key购买 nike

我需要在 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>

问题在于与模型的两种方式绑定(bind)。这是它在后端的样子:

  [HttpPut]
[Route("Update/{id}")]
public async Task<HttpResponseMessage> Update(int id, DepartmentModel model)

问题在于,当我点击编辑模型时,我的 int id 传递给后端,但我的模型 id(应该与传递的 id 相同)为空。此外,当我单击编辑按钮时,我无法看到输入模型值时 View 的变化。在 Angular 1 中,我很快解决了它,但在 Angular 2 中却很困难。关键是我希望 id 在我单击编辑时自动与我的模型连接,并且我可以在输入字段(以及其他 2 个属性)中看到它。感谢您的帮助!

最佳答案

我会使用 ngModel 来解决这个问题。选择元素时,您可以在组件中设置属性 selectedDepartment 以更新部门。然后,您可以将此对象的属性绑定(bind)到输入上(仅您要更新的属性)。

selectedDepartment 对象包含包含当前标识符的所有属性。

单击“保存”按钮时,您可以发送此对象而不是表单值。这样您就不会丢失标识符。

表单代码如下:

<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>

关于angularjs - 更新模型时 Angular 2 中的双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35491964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com