用于textarea的ngModel在angular 2中不起作用 [英] ngModel for textarea not working in angular 2
本文介绍了用于textarea的ngModel在angular 2中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用ngModel
在textarea中打印json对象.
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>
我想在textarea中加载json对象.上面的代码将rapidPage
对象加载到textarea中,但将textarea值显示为[object Object]
.
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]
.
对象:
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?
推荐答案
假设您想按原样绑定rapidPage
,并且只会在textArea中写入有效的JSON.
Assuming that you want to bind rapidPage
as it is and will only write valid JSON in the textArea.
- 更改值时需要
PARSE
,在文本区域中显示时需要STRINGIFY
.
- You need to
PARSE
it when changing the value, andSTRINGIFY
when showing in textarea.
在组件代码中执行以下操作
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');
};
}
模板用法:
<textarea [(ngModel)]='rapidPageValue' rows="30" cols="120">
</textarea>
这篇关于用于textarea的ngModel在angular 2中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文