I am trying to print json object in textarea using ngModel.

我做了以下工作:

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

我想在文本区域中加载json对象.上面的代码在textarea中加载rapidPage对象,但它将textarea值显示为[object Object].

object:

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

我想将数据加载为字符串. 有什么意见吗?

推荐答案

假设您希望按原样绑定rapidPage,并且只在textArea中写入有效的JSON.

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

StackBlitz DEMO

Do the following in your Component code

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

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

  set rapidPageValue (v) {
    try{
    this.rapidPage = JSON.parse(v);}
    catch(e) {
      console.log('error occored while you were typing the JSON');
    };
  }

Template Usage:

<textarea [(ngModel)]='rapidPageValue' rows="30" cols="120">                             
</textarea>

Json相关问答推荐

如何使用JQ将JSON字符串替换为解析后的类似功能?

如何将加权边列表导出到JSON树?

Jolt变换将字段移动到数组的每个元素中

PowerShell:使用JSON原生的Short命令处理JSON?

Jolt - 如何比较 if else 条件的两个值

Jolt 不打印任何东西

从 oracle 数据库中的 json blob 打印值

Powershell v7 文本背景突出显示

通过 xslt 将内部 json 转换为 xml 时遇到问题

Go - JSON 验证抛出错误,除非我在 struct 中使用指针.为什么?

TSQL FOR JSON 嵌套值

解析 JSON API 响应

Angular 2/Web Api - json 解析错误语法错误意外结束输入

如何一次加载无限滚动中的所有条目以解析python中的HTML

将 Objective-C 对象序列化和反序列化为 JSON

在视图中将 .Net 对象转换为 JSON 对象

如何将有向无环图 (DAG) 存储为 JSON?

使用 Python 3 读取 JSON 文件

POST:在 url 本身中发送 post 请求

如何使用 Gson 解码具有未知字段的 JSON?