如何创建Angular 2指令来解析主题标签并创建单击事件?

时间:2017-06-23 06:12:54

标签: javascript angular angularjs-directive ionic2

我有一个Ionic 2(Angular 2)应用程序,它有一个div,文本可能包含主题标签。我需要创建一个解析文本的指令,并为每个#标签替换带有类和click事件的span:

    <div>I am a post that includes #hashtag1 and #hashtag2<div>

应该成为:

    <div>I am a post that includes 
      <span class="hashtag" (click)="gotoHashtag('hashtag1')>#hashtag1</span> 
      and 
      <span class="hashtag" (click)="gotoHashtag('hashtag2')>#hashtag2</span>
    </div>

在我的Ionic 1应用程序(角度1)中,我使用了angular-hashtagify指令:https://github.com/rossmartin/angular-hashtagify

我正在尝试为我的Ionic 2应用制作一个角度2版本。到目前为止,我有:

import {Directive,ElementRef,Renderer} from '@angular/core';
import {NavController} from 'ionic-angular';
import {HashtagPage} from '../pages/hashtag/hashtag';

@Directive({
    selector:'[hashtagify]'
})
export class HashtagifyDirective{

constructor(private el:ElementRef, private render:Renderer, public navCtrl: NavController){
}

private addHashtag() {
    setTimeout(()=> {
       let content = this.el.nativeElement.innerHTML;
       let newcontent = content.replace(/(^|\s)*#(\w+)/g, '$1<span class="hashtag">#$2</span>');
        this.render.setElementProperty(this.el.nativeElement, 'innerHTML', newcontent);
        this.render.listen(this.el.nativeElement, 'click', (event) => {
            event.stopPropagation();
            event.preventDefault();
            let hashtag = event.target.innerText;
            this.navCtrl.push(HashtagPage, {'hashtagTitle': hashtag.substring(1, hashtag.length)});
         });
     },1);
}

     ngOnInit(){
        this.addHashtag();
     }
}

此代码正确设置了标签的样式,但它将click事件放在div而不是span上。我只需要一点帮助就可以在每个包含格式化标签的跨度上放置click事件。我的猜测是我必须为每个span使用渲染器的addElement函数,然后将click事件添加到该新元素,但我不确定如何。谢谢你尽你所能的帮助。

1 个答案:

答案 0 :(得分:1)

我希望这就是你想要的东西

修改添加HashTag方法点击事件列表器

private addHashtag() {
          setTimeout(()=> {

        let content = this.el.nativeElement.innerHTML;

        let newcontent = content.replace(/(^|\s)*#(\w+)/g, '$1<span class="hashtagColored">#$2</span>');
            this.render.setElementProperty(this.el.nativeElement, 'innerHTML', newcontent);
            this.render.listen(this.el.nativeElement, 'click', (event) => 
            if(event.srcElement.classList.contains('hashtagColored')){
              console.log(); // this is the if that checks the class
                event.stopPropagation();
                event.preventDefault();
                let hashtag = event.target.innerText;
                this.navCtrl.push(Page1, {'hashtagTitle': hashtag.substring(1,hashtag.length)});
            });
          },1);
    }

Plunker Link - http://plnkr.co/edit/Y5wAVyhOPJNViGdYJ9d5?p=preview