I am trying to print json object in textarea using ngModel
.
I have done following:
For binding textarea values in Angular 2 you can use the change-function:
<textarea id="some-value" (change)="doTextareaValueChange($event)">{{textareaValue}}</textarea>
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%!.
As per documentation [()] is for two way syntax sugar to remove the boilerplate. What event is being invoked at this? Irrespective, you can put a string output also alongwith the event in below code
Probably try the below code implemetation for your string output
@Directive({
selector: '[ngModel]',
host: {
"[value]": 'ngModel',
"(input)": "ngModelChange.next($event.target.value)"
}
})
class NgModelDirective {
@Input() ngModel:any; // stored value
@Output() ngModelChange:EventEmitter; = new EventEmitter() // an event emitter
}
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>
ngModel works if
If you not you can use the following syntax to achieve the same effect
<textarea [value]="strVariableInComponent" (input)="strVariableInComponent = $event.target.value;"></textarea>