2017-09-28 64 views
1

我有一个伪问题...(在前端侧完全noobie)角双向绑定和映射在UI

我建立一个小的CRUD项目,角4和打字稿,我打电话给一个API以便根据ID获取和更新电话号码。

这是我从服务中获得的电话号码是非常标准的,并在3个部分分为:

  1. 国家代码
  2. 预拨
  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中进行这种映射?什么是好的做法?

回答

1

你可以分裂的ngModel结合:

<text-input [formControl]="form.controls['phoneCountryCodeAndPredial']" 
    name="countryCodeAndPredial" 
    class="required" 
    placeholder="Predial" 
    [ngModel]="contacts.phoneNumber.countryCode + contacts.phoneNumber.predial" 
    (ngModelChange)="Utils.setCombinedNumber(contacts.phoneNumber, $event)" 
> 

然后设置模式变革的正确字段:

setCombinedNumber(phoneNumber: PhoneNumber, combined: string) { 
    // your actual splitting code here 
    let pattern = new RegExp(/^(\+\d{2})(\d+)$/); 
    if (pattern.test(combined)) { 
    let match = pattern.exec(combined); 
    phoneNumber.countryCode = match[1]; 
    phoneNumber.predial = match[2]; 
    } 
    else { 
    // do some error handling here? maybe show a toast? 
    } 
} 
+0

上午我居然允许做这样的操作? ('contacts.phoneNumber.countryCode + contacts.phoneNumber.predial')。这看起来很腥:)但我会尝试!谢谢 – lapadets

+0

总的来说,你只是绑定引号之间的任何值:) – rinukkusu

+0

我试过了,但是当我这样做,并且进入编辑页面时,“预测”输入字段爆炸了:D ie I get例如:'+ 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44 + 44555':D而不是仅仅是'+ 44555' – lapadets