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?
The Angular uses the ngModel directive to achieve the two-way binding on HTML Form elements. It binds to a form element like input , select , selectarea . etc. Internally It uses the ngModel in property, binding to bind to the value property and ngModelChange which binds to the input event.
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value.
To fix Can't bind to 'ngModel' since it isn't a known property of 'input' error in Angular applications we have to import FormModule in app. module. ts file. If you are using FormBuilder class to create reactive form we have to import ReactiveFormsModule as well to avoid below error.
The ngmodel directive is not part of the Angular Core library. It is part of the FormsModule library. You need to import the FormsModule package into your Angular module. If you want to create a form in angular app then you need to import FormsModule from @angular/forms library.
Assuming that you want to bind rapidPage
as it is and will only write valid JSON in the textArea.
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>
<textarea class="form-control" name="message" rows="8" [(ngModel)]="Obj.message" #message='ngModel' ></textarea>
for Two way binding You just need to add attribute in textarea tag name="message"
, ONLY [(ngModel)]
works 100%!.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With