加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

微小的Mce双向绑定与Angular 2/4

发布时间:2020-12-17 17:33:50 所属栏目:安全 来源:网络整理
导读:这是我的tinymce.component.ts import { Component,OnDestroy,AfterViewInit,EventEmitter,Input,Output} from '@angular/core';@Component({ selector: 'simple-tiny',template: `textarea id="{{elementId}}"/textarea`})export class SimpleTinyComponent
这是我的tinymce.component.ts

import {
  Component,OnDestroy,AfterViewInit,EventEmitter,Input,Output
} from '@angular/core';

@Component({
  selector: 'simple-tiny',template: `<textarea id="{{elementId}}"></textarea>`
})
export class SimpleTinyComponent implements AfterViewInit,OnDestroy {
  @Input() elementId: String;
  @Output() onEditorKeyup = new EventEmitter<any>();

  editor;

  ngAfterViewInit() {
    tinymce.init({
      selector: '#' + this.elementId,plugins: ['link','paste','table'],skin_url: 'assets/skins/lightgray',setup: editor => {
        this.editor = editor;
        editor.on('keyup',() => {
          const content = editor.getContent();
          this.onEditorKeyup.emit(content);
        });
      },});
  }

  ngOnDestroy() {
    tinymce.remove(this.editor);
  }
}

现在我正在使用它我的html现在我可以通过keyupHandlerFunction获取文本,但我想要与ngModel 2路绑定

<simple-tiny
      [elementId]="'my-editor-id'"
      (onEditorKeyup)="keyupHandlerFunction($event)"
     >
</simple-tiny>

这段代码是tinyMCE建议的,但我想在这里使用ngModel
对于2路绑定我怎么能在这里做

喜欢:

<simple-tiny
      [elementId]="'my-editor-id'"
      (onEditorKeyup)="keyupHandlerFunction($event)"
      [(ngModel)]="value">
</simple-tiny>

<p>{{ "My Model" + model}} </p>

解决方法

你应该实现这样的 ControlValueAccessor:

export const TINYMCE_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,useExisting: forwardRef(() => SimpleTinyComponent),multi: true
};

@Component({
  selector: 'simple-tiny',template: `<textarea #textArea [value]="value"></textarea>`,providers: [TINYMCE_VALUE_ACCESSOR]
})
export class SimpleTinyComponent implements AfterViewInit,ControlValueAccessor {
  @Input() elementId: String;

  @ViewChild('textArea') textArea: ElementRef;

  editor: any;

  value: string;

  onChange = (_: any) => { };

  constructor(private zone: NgZone) {}

  writeValue(value: any): void {
    this.value = value;
    if (this.editor) {
       this.editor.setContent(value || '');
    }
  }

  ngAfterViewInit() {
    tinymce.init({
      target: this.textArea.nativeElement,() => {
          const content = editor.getContent();
          this.zone.run(() => this.onChange(content))
        });
      }
    });
  }

  registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
  registerOnTouched(fn: () => void): void { }

  ngOnDestroy() {
    tinymce.remove(this.editor);
  }
}

Stackblitz Example

Example inside form

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读