Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

typescript - angular2 wysiwyg tinymce implementation and 2-way-binding

Hi I'm trying to implement tinymce into an angular 2 component for a small forum to create a new thread. I want the content of the textarea (tinymce) be 2-way-binded to a variable inside the component. So far the submit button works but the keyup event doesn't.

export class ForumNewThreadComponent implements OnInit{

  constructor(){}
  ngOnInit():any {
    tinymce.init(
      {
        selector: ".tinyMCE",
      })
  }

text:string;
  submit(){
    this.text = tinymce.activeEditor.getContent();
  }
  getTinymceContent(){
    this.text = tinymce.activeEditor.getContent();
  }
}

and view

<div class="thread-body">
    {{getValue}}
    <textarea class="tinyMCE" style="height:300px" (keyup)="getTinymceContent()">

    </textarea>
    <button class="btn btn-primary" (click)="submit()">Submit</button>
  </div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would implement a custom value accessor for this:

const TINY_MCE_VALUE_ACCESSOR = new Provider(
  NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => TinyMceValueAccessor), multi: true});

@Directive({
  selector: 'textarea[tinymce]',
  host: { '(keyup)': 'doOnChange($event.target)' },
  providers: [ TINY_MCE_VALUE_ACCESSOR ]
})
export class DateValueAccessor extends DefaultValueAccessor {
  @Input()
  tinymce:any;

  onChange = (_) => {};
  onTouched = () => {};

  writeValue(value:any):void {
    if (value!=null) {
      super.writeValue(value.toString());
    }
  }

  doOnChange(elt) {
    this.onChange(this.tinymce.activeEditor.getContent());
  }
}

I would use it this way:

<textarea [tinymce]="tinymce" style="height:300px" [(ngModel)]="text">

</textarea>

and in your component class:

@Component({
  (...)
  directives: [ DateValueAccessor ]
}) 
export class ForumNewThreadComponent implements OnInit{
  constructor(){}
  ngOnInit():any {
    tinymce.init({
      selector: "[tinymce]"
    })
  }

  text:string;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...