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:我try 过使用Ngx-monaco,但由于其他错误而失败'

推荐答案

Textarea元素不支持直接在其中呈现HTML内容.Here is similar question.如果是angular,您不需要在.ts文件中创建带有html字符串的字符串作为内容.使用*ngFor/ @for*ngIf/@if创建您需要的html struct (使用divspan),然后重写您从该SON获得的键/值,并使用绑定将它们分配给span,如下所示:

<div class="some-class-to-look-like-textarea-before">
    <span *ngFor="let spanColor of parsedColors" [style.color]="spanColor">Your text here</span>
</div>

Html相关问答推荐

Blazor中有1像素高行的表格

NG8004:找不到名为""的管道.'' [插件Angular 编译器]

只有一行上有溢出的CSS网格

如何仅 Select 与子代CSS类匹配的第一个元素

Angular 15 p-对话框不使用组件 Select 器呈现HTML

在Quarto/Discrealjs演示文稿中只增加一个列表的填充

仅在加载视频时显示描述(<;Video>;标签)

嵌套表列高度不是100%高度的问题

我无法从带Angular 的Bootstrap 5中的表单中获取数据

如何在垂直堆叠的表格中调整人造列的大小?

如何突破安莉得分

如何在css中旋转块时调整内容宽度、高度

顶部有文字的图像的悬停效果

perl hdb 调试器:浏览器以错误的编码显示 UTF-8 源代码

将箭头图标添加到工具提示包装器时遇到问题

如何围绕中心zoom svg 并使父级达到其子级大小的 100%

如何将自定义图像插入 Shiny plot header?