【问题标题】:Angular not performing two way binding for ngModelAngular 没有为 ngModel 执行双向绑定
【发布时间】:2019-01-02 01:54:50
【问题描述】:

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

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 值的问题吗?

Plunkerhere

【问题讨论】:

  • 您是否在 AppModule 中导入了 FormsModule?
  • 是的,我是在 AppModule 中完成的
  • 可以分享一下使用ngModel的代码吗?
  • 当然。我正在制作小提琴..
  • 我添加了一个 plunker 供您参考。谢谢

标签: angular angular2-ngmodel


【解决方案1】:

根据提供的plunker:

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

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

为了修复它,你可以定义两个变量:

preCounter = 2;
postCounter = 4;

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

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

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

新的解决方案:

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

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})`;
  }
}

【讨论】:

  • 你的意思是在组件本身而不是在 HTML 中拆分值并绑定?
  • 是的,您可以使用两个变量来跟踪计数器,这种方法更加一致。
  • 当然。因为我有这样做的限制,我想在 HTMl 中尝试同样的方法。无论如何都会检查
  • 我开发了建议的解决方案。你能检查一下吗
猜你喜欢
  • 2020-09-12
  • 2017-04-29
  • 2017-08-28
  • 2017-10-20
  • 2016-10-12
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
  • 2017-03-23
相关资源
最近更新 更多