2016-02-18 69 views
1

我需要在角2雙向更新模型

我更新的方法來更新我的模型時,在角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> 

問題出在2種方式與模型綁定。這是它的外觀在後端:

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

的問題是,當我點擊編輯模式,我INT ID傳遞到後端,但我的模型ID(應當網元一樣傳入ID)爲null 。另外,當我點擊編輯按鈕時,我無法看到在爲模型輸入值時如何改變視圖。在角1我快速解決它,但在角2是鬥爭。關鍵是,我想要id自動連接到我的模型,當我點擊編輯,我可以看到它在輸入字段(以及其他2個屬性)。感謝幫助!

回答

1

我會用ngModel來解決這個問題。選擇元素時,可以在組件中設置屬性selectedDepartment並更新部門。您可以在輸入上綁定此對象的屬性(僅限您要更新的屬性)。

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

你的意思是[(ngModel)],而不是[(ngForm)],某事像這樣:[(ngModel)] =「selected.departmentNo :)我也試過,但問題是當我點擊我的編輯按鈕時,在表單輸入字段中沒有來自我的表格行的值。在Angular 1中很容易,不知道是什麼問題。 –

+0

我得到的錯誤:TypeError:無法在AppComponent @ 76:32的[selected.departmentNo]中讀取undefined屬性'departmentNo' –