我正在尝试使用 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
。
在您的组件代码中执行以下操作
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/