ngModel for textarea not working in angular 2
For binding textarea values in Angular 2 you can use the change-function:
Template
<textarea id="some-value" (change)="doTextareaValueChange($event)">{{textareaValue}}</textarea>
Component
export class AppComponent implements OnInit {
private textareaValue = '';
doTextareaValueChange(ev) {
try {
this.textareaValue = ev.target.value;
} catch(e) {
console.info('could not set textarea-value');
}
}
}
Unless you really want to have sync in between, you would normally implement a button to save/apply the change when it's finished json editing. If that is the case, your render is easy.
<textarea #textbox>{{ rapidPage | json }}</textarea>
Make sure no other space or return character in between the above line.
Then an traditional button, ex.
<a (click)="updateRapidPage(textbox.value)">Apply</a>
I found this is better in some case than brutal [(rapidPage)]
.
You can also use @ViewChild('textbox') input
inside the component to access this variable.
<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%!.
Assuming that you want to bind rapidPage
as it is and will only write valid JSON in the textArea.
- You need to
PARSE
it when changing the value, andSTRINGIFY
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>