在angular项目中使用wangeditor,并且给它添加palceholder功能

最近维护开发的项目遇到一个需求,希望项目中的富文本编辑器能有一个类似input输入框的placeholder功能,其实我是拒绝的,又不是不能用T.T

查看wangeditor文档发现本身没有提供该功能,不过作者在其github的issue中给出了一点思路

需求确认

前人封装的除了没有placeholder这个功能之外,也还行,但感觉缺少了一些东西,比如双向数据绑定,非空检验(控制外部按钮状态,比如置灰发布按钮)

先列一下需求吧

  1. 使用wangeditor(基本要求了...)

  2. 双向数据绑定

  3. 实现placeholder支持自定义

模板和样式

  1. 模板

    <div class="wangeditor-wrapper">
      <div #wangeditor></div>
      <span
        class="placeholder"
        [style.display]="showPlaceholder ? 'inline' : 'none'"
        >{{ placeholder }}</span
      >
    </div>

     

  2. 样式

    我这里是根据工具条的告诉调了一个比较合适的位置,不是很完美,比如能否实现工具条支持换行的情况下,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的状态判断是否空内容

利用typescriptget属性

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组件都一样,不过多赘述,只说一下思路

  1. 标记输入输出属性

    @Input() content: string = ''
    @Output() contentChange = new EventEmitter()

     

  2. 编辑器初始化之后设置内容

    this.editor.txt.html(this.content)

     

  3. 编辑器内容改变的时候发射自定义事件

    this.editor.customConfig.onchange = (html) => {
          this.contentChange.emit(html)
        }

     

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值