You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular文本编辑器:实现点击添加/移除<strong>标签功能求助

解决方案:为选中文本添加/移除<strong>标签

你的核心问题是之前的方法仅修改了textarea的样式,没有实际修改文本内容添加<strong>标签,且无法针对选中文本操作。以下是实现需求的具体方案:

修改后的HTML代码

添加触发加粗/取消加粗的按钮,同时保留原有的表单结构:

<mat-form-field appearance="outline">
  <mat-label>textarea</mat-label>
  <textarea #myTextArea matInput formControlName="editor"></textarea>
</mat-form-field>
<button (click)="toggleBold()">加粗/取消加粗</button>
<button (click)="add()">输出内容</button>

修改后的TS代码

重写toggleBold方法,实现选中文本的标签包裹与移除逻辑:

import { Component, ElementRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.css']
})
export class EditorComponent {
  @ViewChild('myTextArea') public textarea: ElementRef;
  public form: FormGroup;

  constructor(private fb: FormBuilder) {
    // 初始化表单控件
    this.form = this.fb.group({
      editor: ['']
    });
  }

  toggleBold() {
    const textareaEl = this.textarea.nativeElement;
    const startPos = textareaEl.selectionStart;
    const endPos = textareaEl.selectionEnd;
    const selectedText = textareaEl.value.substring(startPos, endPos);

    // 无选中文本时不执行操作
    if (!selectedText) return;

    let newText: string;
    let newCursorPos: number;

    // 判断选中文本是否已被<strong>包裹
    if (selectedText.startsWith('<strong>') && selectedText.endsWith('</strong>')) {
      // 移除标签,恢复原文本
      newText = selectedText.slice(8, -9);
      newCursorPos = startPos + newText.length;
    } else {
      // 添加<strong>标签包裹选中文本
      newText = `<strong>${selectedText}</strong>`;
      newCursorPos = startPos + newText.length;
    }

    // 更新textarea内容与表单值
    const updatedValue = textareaEl.value.substring(0, startPos) + newText + textareaEl.value.substring(endPos);
    this.form.get('editor')?.setValue(updatedValue);

    // 恢复光标位置(可选,提升用户体验)
    setTimeout(() => {
      textareaEl.selectionStart = newCursorPos;
      textareaEl.selectionEnd = newCursorPos;
    }, 0);
  }

  add() {
    console.log(this.form.value);
  }
}

关键逻辑说明

  1. 获取选中范围:通过textarea的selectionStart和selectionEnd属性获取选中文本的起始、结束位置,提取选中内容。
  2. 标签判断:检查选中文本是否已被<strong>标签包裹,以此决定是添加还是移除标签。
  3. 内容替换:将选中文本替换为带标签(或移除标签)的内容,更新整个textarea的值并同步到表单控件。
  4. 光标恢复:通过setTimeout延迟设置光标位置,确保表单值更新后光标能回到正确位置,避免用户操作中断。

内容的提问来源于stack exchange,提问作者foo42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:05:24