我有一個僞問題...(在前端側完全noobie)角雙向綁定和映射在UI
我建立一個小的CRUD項目,角4和打字稿,我打電話給一個API以便根據ID獲取和更新電話號碼。
這是我從服務中獲得的電話號碼是非常標準的,並在3個部分分爲:
- 國家代碼
- 預撥
- 實際數量
但是在UI,實際上我有兩個輸入字段 - 一個用於國家代碼和一起預測,另一個用於實際數字。爲直觀起見,如果電話號碼,我從用戶得到的是+445551234567
當我編輯它,我有+44555
兩個輸入字段和1234567
換句話說,我必須映射國家代碼+在UI一起預撥在我的編輯頁面中,當我將更新調用回API時,我需要能夠將它重新映射到3個變量。
在理想的世界中,我會將其映射到我的服務中,但由於其他限制,這是不可能的。
所以我有這些型號/接口:
export interface Contacts {
email: string;
phoneNumber: PhoneNumber;
faxNumber: PhoneNumber;
}
export interface PhoneNumber {
countryCode: string;
predial: string;
number: string;
}
然後在我的輸入組件我有一個表格:
this.form = new FormGroup({
phoneCountryCodeAndPredial: new ValidatableFormControl(null, [Validators.required]),
phoneNumber: new ValidatableFormControl(null, [Validators.required]),
faxCountryCodeAndPredial: new ValidatableFormControl(null, [Validators.required]),
faxNumber: new ValidatableFormControl(null, [Validators.required]),
email: new ValidatableFormControl(null, [Validators.pattern(/\[email protected]\S+\.\S+/)])
});
而在HTML剛剛的電話號碼爲簡潔:
<div class="form-group-line">
<input [formControl]="form.controls['phoneCountryCodeAndPredial']" name="countryCodeAndPredial"
class="required"
placeholder="Predial"
[(ngModel)]=contacts.phoneNumber.countryCode/>
<input [formControl]="form.controls['phoneNumber']" name="phoneNumber"
class="required"
placeholder="Phone Number"
[(ngModel)]="contacts.phoneNumber.number"/>
</div>
所以我想雙向數據綁定,這就是爲什麼我使用[(ngModel)] banana in the box
,但我該如何使用ngModel中的雙向數據綁定+映射?
我無法將國家代碼和預測結合在一起並將值傳遞給ngModel。
那麼如何在UI中進行這種映射?什麼是好的做法?
上午我居然允許做這樣的操作? ('contacts.phoneNumber.countryCode + contacts.phoneNumber.predial')。這看起來很腥:)但我會嘗試!謝謝 – lapadets
總的來說,你只是綁定引號之間的任何值:) – rinukkusu
我試過了,但是當我這樣做,並且進入編輯頁面時,「預測」輸入字段爆炸了:D ie I get例如:'+ 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44555':D而不是僅僅是'+ 44555' – lapadets