如何在Angular中实现文本加粗样式?自定义编辑器开发遇阻
文本编辑器加粗功能实现方案
你的问题出在这几个核心点:
- textarea的用户输入内容存在
value属性里,不是innerHTML,用innerHTML无法获取有效文本 bold()是字符串方法,只会返回包裹<strong>标签的新字符串,但你没有把结果赋值回textarea,也没处理文本选中的场景
下面是修正后的完整代码:
HTML部分
<div class="content"> <!-- toolbar --> <div class="toolbar-content"> <!-- bold --> <span (click)="addBoldStyle()"> <mat-icon>format_bold</mat-icon> </span> </div> </div> <!-- textarea --> <form [formGroup]="form"> <div class="textarea"> <mat-form-field appearance="outline" style="width: 470px;"> <mat-label>textarea</mat-label> <textarea #text matInput formControlName="editor" rows="5" style="border-radius: 5px"></textarea> </mat-form-field> </div> </form>
TypeScript部分
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('text') public textarea: ElementRef<HTMLTextAreaElement>; public form: FormGroup; constructor(private fb: FormBuilder) {} ngOnInit(): void { this.createForm(); } createForm() { this.form = this.fb.group({ editor: null, }); } addBoldStyle() { const textarea = this.textarea.nativeElement; const start = textarea.selectionStart; const end = textarea.selectionEnd; const selectedText = textarea.value.substring(start, end); // 无选中文本时,在光标位置插入空加粗标签并定位光标 if (!selectedText) { const boldText = '<strong></strong>'; const newText = textarea.value.substring(0, start) + boldText + textarea.value.substring(end); textarea.value = newText; textarea.selectionStart = textarea.selectionEnd = start + 8; } else { // 有选中文本时,用加粗标签包裹选中内容 const boldText = `<strong>${selectedText}</strong>`; const newText = textarea.value.substring(0, start) + boldText + textarea.value.substring(end); textarea.value = newText; textarea.selectionStart = start; textarea.selectionEnd = start + boldText.length; } // 同步表单控件值,保持数据一致 this.form.get('editor')?.setValue(textarea.value); } }
关键说明
- 先获取textarea的选中范围,区分两种交互场景:选中文本加粗、未选中文本插入加粗模板
- 操作完成后同步表单控件的值,确保表单数据和textarea内容匹配
内容的提问来源于stack exchange,提问作者foo42
相关产品推荐
相关产品推荐

