我得到的是一个动态生成的 ngModel 对象,并且某些不在顶层的属性仅在一个方向上绑定(bind)。
包括一个应该让事情变得更清晰的 plunkr,但我想做的是生成一个动态表单,并且如果属性嵌套在根下方的某个级别,则可以使用对象括号表示法。我唯一的想法是,也许将三元运算符放入 ngModel 中是一种不好的形式,但我在尝试从 ngModel 中调用函数时遇到了错误。
在这里: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'};
}
如果动态输入没有在一个方向上绑定(bind),我会知道要修复什么,但现在我不确定我在这里缺少什么。
最佳答案
尝试使用(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
关于javascript - Angular 2+ ngModel 仅使用对象括号表示法在嵌套值上绑定(bind)动态 ngModel 的一种方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44315934/