Angular自定义编辑器:选中文本加粗及添加<strong>标签问题求助
解决方案
1. 替换文本框为支持HTML的可编辑元素
原生<textarea>仅能处理纯文本,无法保存<strong>这类HTML标签,因此需要替换为contenteditable容器元素(比如<div>):
修改HTML代码:
<form [formGroup]="form"> <div> <mat-form-field appearance="outline"> <mat-label>editor</mat-label> <div #text contenteditable="true" (input)="syncEditorValue()" class="editor-content" ></div> </mat-form-field> </div> </form>
添加基础样式(让编辑器外观接近文本框):
.editor-content { min-height: 100px; padding: 8px; border: 1px solid rgba(0,0,0,.12); border-radius: 4px; outline: none; }
2. 实现选中文本加粗/添加<strong>标签
修改TS中的addBoldStyle方法,通过浏览器原生API操作选中文本:
@ViewChild('text') public editor: ElementRef; public form: FormGroup; constructor(private fb: FormBuilder) {} ngOnInit(): void { this.createForm(); } createForm() { this.form = this.fb.group({ editor: null, }); } // 同步可编辑元素内容到表单控件 syncEditorValue() { this.form.patchValue({ editor: this.editor.nativeElement.innerHTML }); } addBoldStyle() { // 聚焦编辑器确保选中状态有效 this.editor.nativeElement.focus(); // 自动给选中文本包裹<strong>标签,已加粗内容会自动取消格式 document.execCommand('bold', false, null); // 同步最新内容到表单 this.syncEditorValue(); } add() { console.log(this.form.value); }
替代实现(不使用execCommand)
若不想用标记为过时但仍广泛兼容的execCommand,可通过Selection API手动处理:
addBoldStyle() { const selection = window.getSelection(); if (!selection.rangeCount) return; const range = selection.getRangeAt(0); const selectedText = range.toString(); if (!selectedText) return; // 创建<strong>标签包裹选中内容 const strong = document.createElement('strong'); strong.appendChild(range.extractContents()); range.insertNode(strong); // 恢复选中状态(可选) selection.removeAllRanges(); const newRange = document.createRange(); newRange.selectNodeContents(strong); selection.addRange(newRange); this.syncEditorValue(); }
内容的提问来源于stack exchange,提问作者foo42
相关产品推荐
相关产品推荐

