I have an Angular application , in this app , i have a text area that i will always write json text to it , what i want is at the same moment that i am writing in this textarea , in case the json is valid, i want the text to be colorfull ( Key with a color and value with another color)(this is something similair to Postman when writing JSON ) .
What i have tried so far :
HTML:
` <textarea
pInputText
placeholder="required name and schemaJson object"
formControlName="schema"
id="schema" rows="10" cols="50" required
(input)="updateTextColor($event.target.value)">
</textarea>````
TypeScript:
updateTextColor(text: string): void {
try {
const jsonObject = JSON.parse(text);
const coloredText = this.colorizeJSON(jsonObject);
document.getElementById('schema').innerHTML = coloredText;
} catch (error) {
// If JSON parsing fails, keep the text as is
document.getElementById('schema').innerText = text;
}
}
colorizeJSON(obj: any): string {
let coloredText = '';
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
coloredText += `<span class="json-key">${key}</span>: `;
if (typeof obj[key] === 'object') {
coloredText += this.colorizeJSON(obj[key]);
} else {
coloredText += `<span class="json-value">${obj[key]}</span>`;
}
coloredText += ', ';
}
}
// Remove trailing comma and return
return coloredText.replace(/,\s*$/, '');
}
PS:i have tried using Ngx-monaco, but failed due to other errors`
Textarea element does not support rendering HTML content directly within it. Here is similar question. In case of angular you don't need to create string with html string as a content in your .ts file. Use *ngFor
/ @for
and *ngIf
/@if
to create html structure you need (using div
s and span
s) and then iterate over key/value you got from that JSON and assign them to the span
s using binding like this:
<div class="some-class-to-look-like-textarea-before">
<span *ngFor="let spanColor of parsedColors" [style.color]="spanColor">Your text here</span>
</div>