在内容可编辑div中设置插入符位置

时间:2018-10-21 20:53:11

标签: javascript html angular typescript

我有一个任务,必须选择一个特定的文本,以防它被井号或@标记。

所以,我做了一个转换此文本的管道:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'tagParse'
})
export class tagParsePipe implements PipeTransform {

  urls: any = /(\b(https?|http|ftp|ftps|Https|rtsp|Rtsp):\/\/[A-Z0-9+&@#\/%?=~_|!:,.;-]*[-A-Z0-9+&@#\/%=~_|])/gim; // Find/Replace URL's in text    
    hashtags: any = /(^|\s)(#[a-z\d][\w-]*)/ig; // Find/Replace #hashtags in text   
    mentions: any = /(^|\s)(@[a-z\d][\w-]*)/ig; // Find/Replace @Handle/Mentions in text    
    emails: any = /(\S+@\S+\.\S+)/gim; // Find/Replace email addresses in text

  transform(text: string) {
    return this.parseUrl(text);
  }

  private parseUrl(text: string) {
    // Find/Replace URL's in text
    if (text.match(this.urls)) {
        text = text.replace(this.urls, function replacer($1, $2, $3) {
            let url: any = $1;
            let urlClean: any = url.replace("" + $3 + "://", "");

            return "<a href=\"" + url + "\" target=\"_blank\">" + urlClean + "</a>";
        });
    }
    // Find/Replace @Handle/Mentions in text
    if (text.match(this.hashtags)) {
      text = text.replace(this.hashtags, "<span class=\"hashtag-link\">$1$2</span>");
    }

    // Find/Replace #hashtags in text
    if (text.match(this.mentions)) {
      text = text.replace(this.mentions, "<span class=\"handle-link\">$1$2</a>");
    }

    // Find/Replace email addresses in text
    if (text.match(this.emails)) {
        text = text.replace(this.emails, "<a href=\"mailto:$1\">$1</a>");
    }
    return text;
  }

,我创建了一个指令,该指令必须将插入符号设置为div中的最后一个位置。因此,这就是问题的关键所在,它无法正常工作,并且始终将插入符号设置为开始。

import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';
import { consumeBinding } from '@angular/core/src/render3/instructions';

@Directive({
  selector: '[setPosition]'
})



export class setPositionDirective {


  constructor(private elRef: ElementRef, ) {}


  @HostListener('input', ['$event'])
  onKeyPress(e: any) {
      this.eventHandler();
  }

  eventHandler() {
    const range = document.createRange();
    const pos = this.elRef.nativeElement.lastChild.textContent.length;
    const sel = window.getSelection();
    console.log('el last child', this.elRef.nativeElement.lastChild.textContent.length,
    typeof(this.elRef.nativeElement.lastChild.textContent.length));
    range.setStart(this.elRef.nativeElement.lastChild, pos);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
  }

}

它在模板中的外观

<div
setPosition
class="textarea" 
contenteditable="true" 
[textContent]="model" 
(input)="model=$event.target.textContent" 
[innerHTML] = "model | tagParse">
</div>

任何想法如何解决?预先谢谢你!

0 个答案:

没有答案
相关问题