代码之家  ›  专栏  ›  技术社区  ›  forgottofly

ngModel角度不执行双向绑定

  •  1
  • forgottofly  · 技术社区  · 7 年前

    我有一个字符串对象数组,其格式为(旧的,新的)值 如:

    this.values= {
      "countByView": {
        "count1": "2(4)",
        "count2": "5(7)",
        "count3": "7(10)"
      }
    }
    

    因为它们是字符串,所以我在显示时使用下面的方法将它们转换为HTML格式。。

    Old value of count 1 : {{values.countByView.count1.toString().split('(')[0]}}     //output :2
    New value of count 1 : {{values.countByView.count1.toString().split('(')[1].slice(0,-1)}})}}  //output:4
    

    效果很好。

    我试着用文本框做双向绑定 即。,

    它绑定count1的值,但在更改时不会被反射回来。

    这是ngModel值的问题吗?

    抢劫犯 here

    1 回复  |  直到 7 年前
        1
  •  1
  •   Raed Khalaf    7 年前

    据提供的劫匪说:

    将输入字段绑定为“count1.toString().split('(')[0]”

    • 当分割字符串值时,它返回一个新引用,这意味着绑定是在新引用上完成的,而不是在count1引用上完成的。

    为了解决这个问题,您可以定义两个变量:

    preCounter = 2;
    postCounter = 4;
    

    然后可以将ngModel绑定到preCounter变量。

    <input [(ngModel)]="preCounter">
    

    ====编辑==============================

    新解决方案:

    我已经更改了您在plunker中提供的代码,我做了一个将count绑定到输入字段的技巧,如下所示:

    import {Component} from '@angular/core';
    
    @Component({
      selector: 'sample-app',
      template: `
        <!-- class gets set here fine - problem with svg? -->
        <h1> Counter: {{count1}} </h1>
        <h1>Old value of count1 : {{count1.toString().split('(')[0]}}</h1>
         <h1>New value of count1 : {{count1.toString().split('(')[1].slice(0,-1)}} </h1>
    
         //If I change anything inside text box,it's not reflecting in Old value of count1
    
         <input type="text" [(ngModel)]="preCounter" name="count1" 
            (keyup)="onCountChange()"
         >
    
      `
    })
    export class AppComponent {
      color: string = 'red';
    
      preCounter = 2;
      postCounter = 4;
    
      count1="2(4)";
    
      // track the change in the input field
      onCountChange() {
        this.count1 = this.preCounter + `(${this.postCounter})`;
      }
    }
    
    推荐文章