Angular 4 contenteditable获取并替换当前单词

时间:2017-10-28 15:08:45

标签: angular contenteditable angular2-directives

我的代码中有这个指令:

@Directive({
  selector: 'div[contentEditable]'
})
export class ContenteditableDirective implements OnChanges {
  @Input() contenteditableModel: string;
  @Output() contenteditableModelChange?= new EventEmitter();
  @Input() contenteditableHtml = false;

  constructor(
    private elRef: ElementRef,
    private sanitizer: Sanitizer
  ) {
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['appContenteditableModel']) {
      if (changes['appContenteditableModel'].isFirstChange() && !this.contenteditableModel) {
        this.onInput(true);
      }
      this.refreshView();
    }
  }

  @HostListener('input')
  @HostListener('blur')
  @HostListener('keyup') onInput(trim = false) {
    console.log('anc');

    let value = this.elRef.nativeElement[this.getProperty()];
    if (trim) {
      value = value.replace(/^[\n\s]+/, '');
      value = value.replace(/[\n\s]+$/, '');
    }
    this.contenteditableModelChange.emit(value);
  }

  @HostListener('paste') onPaste() {
    this.onInput();
    if (!this.contenteditableHtml) {
      setTimeout(() => {
        if (this.elRef.nativeElement.innerHTML !== this.elRef.nativeElement.innerText) {
          this.elRef.nativeElement.innerHTML = this.elRef.nativeElement.innerText;
        }
      });
    }
  }

  private refreshView() {
    const newContent = this.sanitize(this.contenteditableModel);
    if (newContent !== this.elRef.nativeElement[this.getProperty()]) {
      this.elRef.nativeElement[this.getProperty()] = newContent;
    }
  }

  private getProperty(): string {
    return this.contenteditableHtml ? 'innerHTML' : 'innerText';
  }

  private sanitize(content: string): string {
    return this.contenteditableHtml ? this.sanitizer.sanitize(SecurityContext.HTML, content) : content;
  }
}

现在我想为click@HostListener('click'))采取另一个操作,该操作会返回被点击的字词,但我不知道如何实施,或者它是否均匀可能的。

我想要做的另一件事是点击它后替换这个词,但我不知道如何开始。

0 个答案:

没有答案