Bhushan Gadekar Bhushan Gadekar - 6 months ago 565
JSON Question

ngModel for textarea not working in angular2

I am trying to print json object in textarea using

ngModel
.

I have done following:

<textarea style="background-color:black;color:white;" [(ngModel)]='rapidPage' rows="30" cols="120">
</textarea>


I want to load the json object in textarea. The above code is loading the
rapidPage
object in textarea but its showing textarea value as
[object Object]
.

object:

this.rapidPage = {
"pageRows": [
{
"sections": [
{
"sectionRows": [
{
"secRowColumns": [
]
},
{
"secRowColumns": [
{
"colName": "users"
}
]
},
{
"secRowColumns": [
{
"colName": "sample"
}
]
}
],
"width": 0
}
]
}
],
"pageName": "DefaultPage",
"pageLayout": "DEFAULT_LAYOUT",
"editMode": true
};


I want to load the data as string.
any inputs?

Answer

Assuming that you want to bind rapidPage as it is and will only write valid JSON in the textArea.

  • You need to PARSE it when changing the value, and STRINGIFY when showing in textarea.

PLUNKER DEMO

Do the following in your Component code

var rapidPage = {...}; // your object

get rapidPageValue () {
  return JSON.stringify(rapidPage, null, 4);
}

get rapidPageValue (v) {
   try {
      rapidPage = JSON.parse(v);}
   catch(e) {
      console.log(`you will have to catch and the erros happening when 
        editing the JSON. Because JSON.parse will throw erro for invalid json`);
    }
}

Template Usage:

<textarea style="background-color:black;color:white;" [(ngModel)]='rapidPageValue' rows="30" cols="120">                             
</textarea>
Comments