2

I have a class with a field that is a JSON object and I need to display this JSON into a textarea. So I have create a set/get method to handle this beavior.

My Class:

class Element {

 property: string;
 value: string;

  constructor(property: string,value: string){

    this.property = property;
    this.value = value;
  }
}

class Model {

   elements: Element[];

   constructor(elements?: Element) { 
       this.elements = elements;
   }

   get elementsValue() {
       return JSON.stringify(this.elements, null, 2);
   }
   set elementsValue(value: string) {
       this.elements = JSON.parse(value);
   }

}

My component:

  @Component({
      selector: 'my-app',
      providers: [],
      template: `
        <div *ngFor="let model of models">
             <textarea [(ngModel)]='model.elementsValue' rows="30" cols="120"></textarea>
        </div>  `,
      directives: []
    })
    export class App {

      models = [
          new Model([new Element("test","value"),new Element("test","value")]),
          new Model()
      ]
    }

The elementsValue value is not bound to the textarea. The textarea is empty

I have use this Plank as template.

theShadow89
  • 1,307
  • 20
  • 44
  • Are you getting an error? What more specifically is happening? And is it possible to change the Plunker to demonstrate *your* issue. That would help us help you. – DeborahK Sep 15 '17 at 16:56
  • the Plunker is not mine. I have use it as a template – theShadow89 Sep 15 '17 at 19:23
  • Yes, but you can click the button in the upper left corner to fork the plunker and then add your code. It would be easier to help you if we can see your code in the context of a running plunker. – DeborahK Sep 15 '17 at 20:18
  • where is your rapidPage variable? I do not see any references to your Objects variable. Check out this similar question: https://stackoverflow.com/questions/37346820/ngmodel-for-textarea-not-working-in-angular2 – Brino Sep 15 '17 at 22:35
  • Do you have to use get/set properties? And you are not creating instant of "Object" (object) when you do "new Model();" Solution would be, creating proper "Object" with properties in Model, instead of doing json stringify or parse. – Basavaraj Bhusani Sep 16 '17 at 10:06
  • Finally, I have found the problem, I create the `Model` as a result of remote API calling like `res.json() as Model`, this way not ceate an instance of the `Model` so `get` end `set` not work. – theShadow89 Sep 18 '17 at 13:12

2 Answers2

0
<div *ngFor="object of objects">

Try

<div *ngFor="let object of objects">
mbnx
  • 912
  • 5
  • 11
0

Your constructor in the Model class expects just a single Element as argument. Try to change that parameter to an array of elements

constructor(elements?: Element[]) {
   this.elements = elements;
} 
Fredrik Lundin
  • 8,006
  • 1
  • 29
  • 35