angularngmodelangular2-ngmodel

Angular - TextArea with Multiple Binding


I have two input field ("name" and "city") and one textarea on my screen. Text area is filled up with some JSON data and data contains a few details like "name", "city", "address", "pin code" etc.

How do I only update "name" or "city" inside textarea when user type something on "name" or "city" input fields.

Is there something to do multiple bindings with textarea ?

Any help would be appreciated.


Solution

  • There is no multiple binding available for such a scenario, however, you can parse the json every change event, and update relevant fields:

    see demo

    @Component({
      selector: "hello",
      template: `
        <textarea (change)="updateObj()" [(ngModel)]="objJson"></textarea>
        {{ obj | json }}
      `,
      styles: [
        `
          h1 {
            font-family: Lato;
          }
        `
      ]
    })
    export class HelloComponent {
      obj = {
        name: "John",
        city: "Chicago"
      };
    
      objJson: string;
    
      constructor() {
        this.objJson = JSON.stringify(this.obj);
      }
    
      updateObj() {
        const tempObj = JSON.parse(this.objJson);
        this.obj.name = tempObj.name;
        this.obj.city = tempObj.city;
        // also possible for a generic update:
        // Object.keys(this.obj).forEach(k => { this.obj[k] = tempObj[k]; });
      }
    }