javascript - textarea 的 ngModel 在 Angular 2 中不起作用

标签 javascript html json angular

我正在尝试使用 ngModel 在 textarea 中打印 json 对象。

我做了以下事情:

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

我想在 textarea 中加载 json 对象。上面的代码在 textarea 中加载 rapidPage 对象,但它显示的 textarea 值是 [object Object]

对象:

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

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

最佳答案

假设您要按原样绑定(bind) rapidPage,并且只会在 textArea 中写入有效的 JSON。

  • 更改值时需要PARSE,在textarea中显示时需要STRINGIFY

StackBlitz DEMO

在您的组件代码中执行以下操作

  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');
    };
  }

模板用法:

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

关于javascript - textarea 的 ngModel 在 Angular 2 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37346820/

相关文章:

javascript - 选择其他选择下拉菜单的选项

javascript - 向文档添加新元素,但表单只是自行刷新

javascript - 如何基于 JSON 创建 HTML 表格

javascript - 如何在reactjs中循环嵌套对象?

html - 生成 html 自定义网格列表项

python - 自定义 simplejson 输出

javascript - React JS,停止生产中显示错误

javascript - 未捕获的安全错误 : Failed to read the 'contentDocument' property from 'HTMLIFrameElement'

javascript - 如何将类别屏幕添加到我正在制作的应用程序中?

html - 当 flexbox 元素以列模式包装时,容器不会增加其宽度