简体   繁体   English

Angular 2+ ngModel仅对带有对象括号表示法的嵌套值绑定动态ngModel的一种方式

[英]Angular 2+ ngModel only binding one way for dynamic ngModel on nested values with Object bracket notation

What I've got is an object for ngModel that's generated dynamically, and certain properties that don't live on the top level are only binding in one direction. 我得到的是动态生成的ngModel对象,某些不在顶层的属性仅在一个方向上绑定。

Including a plunkr that should make things clearer, but what I'm trying to do is generate a dynamic form and if a property is nested at a level beneath the root to use object bracket notation. 包括一个应该使事情更清楚的plunkr,但是我想做的是生成一个动态表单,并且是否将属性嵌套在根目录下的某个级别以使用对象括号表示法。 My only thought is maybe putting the ternary operator in ngModel is bad form, but I've run into errors just trying to call a function from within ngModel. 我唯一的想法可能是将三元运算符放在ngModel中是错误的形式,但是我尝试从ngModel中调用函数时遇到了错误。

Plunkr here : https://plnkr.co/edit/UPrem6 在这里的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'};
}

If that dynamic input wasn't binding in one direction, I'd have some idea of what to fix, but for now I'm not sure what I'm missing here. 如果该动态输入未在一个方向上具有约束力,那么我将对要解决的问题有所了解,但是现在我不确定在这里缺少什么。

Try using (ngModelChange) like 尝试使用(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 改装柱塞

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM