Angular not performing two way binding for ngModel


I have an array of string objects that are in the format of (old,new) values

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

As they are string I’m transforming them in HTML using below method while displaying..

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

which works fine.

I was trying to do two way binding with help of a text box

which binds the value of count1 but on change it dosen’t get reflected back.

Is this the problem with the ngModel value ?

Plunker here


According to the provided plunker:

you bind the input field with “count1.toString().split(‘(‘)[0]”

  • when you split the string value it returns a new reference, this means the binding is done on the new reference not no the count1 reference.

in order to fix it, you can define two variables:

preCounter = 2;
postCounter = 4;

and then you can bind the ngModel to preCounter variable.

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

============================ EDIT ==============================

new solution:

i’ve have changed the code you provided in plunker, i did a trick of binding the count to the input field as follow:

import {Component} from '@angular/core';

  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" 

export class AppComponent {
  color: string = 'red';

  preCounter = 2;
  postCounter = 4;


  // track the change in the input field
  onCountChange() {
    this.count1 = this.preCounter + `(${this.postCounter})`;

Answered By – Raed Khalaf

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.