2017-06-01 71 views
0

我得到的是ngModel的一個對象,它是動態生成的,某些不在頂層的屬性只是綁定的在一個方向。Angular 2+ ngModel只綁定一個方法用動態ngModel對對象括號表示的嵌套值

包括一個應該使事情更清晰的plunkr,但我想要做的是生成一個動態表單,並且如果一個屬性嵌套在根下面的級別以使用對象括號表示法。我唯一的想法可能是把ngModel中的三元運算符放在壞模式中,但是我只是試圖從ngModel中調用一個函數而遇到錯誤。

Plunkr這裏:https://plnkr.co/edit/UPrem6

@Component({ 
    selector: 'sample-app', 
    template: ` 
     <h5>The first input binds both ways Up and Down to the value. The second input only binds to values coming down from the component not upwards!</h5> 
     <label>Manual binding </label><input type="text" [(ngModel)]="contact['businessAddress']['line1']"/><br/> 
     <label>Dynamic binding (Changing this doesn't update manual binding) </label><input type="text" [(ngModel)]="field.subKey ? contact[field.submitKey][field.subKey] : contact[field.submitKey]"/> 
     ` 
}) 
export class AppComponent { 
    contact = {businessAddress:{line1:'default value'}}; 
    field = {submitKey:'businessAddress',subKey:'line1'}; 
} 

如果動態輸入不是在一個方向結合,我有什麼解決一些想法,但現在我不知道我是什麼在這裏失蹤。

回答

2

嘗試使用(ngModelChange)

<input type="text" 
      [ngModel]="field.subKey ? 
        contact[field.submitKey][field.subKey] : 
        contact[field.submitKey]" 
    (ngModelChange)="field.subKey ? 
        contact[field.submitKey][field.subKey] = $event : 
        contact[field.submitKey] = $event"/> 

Modified Plunker

+0

你修改普拉克似乎工作,你會得到了投票了。如果它在我的應用程序中起作用,我會接受正式的答案!謝謝! – chairmanmow

+0

不客氣! – yurzui

+0

它的工作!公認! – chairmanmow

相關問題