最近维护开发的项目遇到一个需求,希望项目中的富文本编辑器能有一个类似input输入框的placeholder功能,其实我是拒绝的,又不是不能用T.T
查看wangeditor文档发现本身没有提供该功能,不过作者在其github的issue中给出了一点思路
需求确认
前人封装的除了没有placeholder这个功能之外,也还行,但感觉缺少了一些东西,比如双向数据绑定,非空检验(控制外部按钮状态,比如置灰发布按钮)
先列一下需求吧
-
使用wangeditor(基本要求了...)
-
双向数据绑定
-
实现placeholder支持自定义
模板和样式
-
模板
<div class="wangeditor-wrapper"> <div #wangeditor></div> <span class="placeholder" [style.display]="showPlaceholder ? 'inline' : 'none'" >{{ placeholder }}</span > </div>
-
样式
我这里是根据工具条的告诉调了一个比较合适的位置,不是很完美,比如能否实现工具条支持换行的情况下,
placeholder
的位置自己跟随.wangeditor-wrapper { position: relative; .placeholder { position: absolute; top: 42px; left: 12px; color: #cccccc; } }
初始化wangeditor
@ViewChild('wangeditor', null) wangeditor: ElementRef
/**
* 初始化wangeditor
*/
initEditor() {
this.editor = new E(this.wangeditor.nativeElement)
this.initEditorConfig()
this.editor.customConfig.onchange = (html) => {
this.contentChange.emit(html)
}
this.editor.create()
if (this.content) {
this.editor.txt.html(this.content)
}
}
实现placeholder
同时可根据placeholder的状态判断是否空内容
利用typescript
的get
属性
get showPlaceholder() {
if (!this.editor) return true
if (this.editor.txt.html().search(/<img src="/i) >= 0) {
return false
}
return !this.editor.txt.text()
}
双向数据绑定
双向数据绑定需要使用到@Input
和@Output
装饰器相互配合实现,实现思路其他angular组件都一样,不过多赘述,只说一下思路
-
标记输入输出属性
@Input() content: string = '' @Output() contentChange = new EventEmitter()
-
编辑器初始化之后设置内容
this.editor.txt.html(this.content)
-
编辑器内容改变的时候发射自定义事件
this.editor.customConfig.onchange = (html) => { this.contentChange.emit(html) }