我有一個Ionic 2(Angular 2)應用程序,其div文本可能包含hashtags。我需要創建一個解析文本指令,併爲每個主題標籤與類和點擊事件,跨度替換它:如何創建一個Angular 2指令來解析hashtags並創建一個click事件?
<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>
在我離子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();
}
}
此代碼正確地設置hashtag的樣式,但它將click事件放置在div上而不是span上。我只需要一點點幫助將click事件放在每個包含格式化hashtag的跨度上。我的猜測是我必須爲每個跨度使用渲染器的addElement函數,然後向該新元素添加一個單擊事件,但我不知道如何。謝謝你盡你所能的幫助。
你可以有一個相同的plunker? –
感謝您嘗試提前提供幫助。它是我第一次試圖建立一個plunkr,但這裏是:https://plnkr.co/edit/rxr51icHWP8vuY11rQZ8?p=preview由於某種原因,該指令在重擊者上根本不起作用。我不知道爲什麼。 – ShawnS582
該指令是不工作在蹲跳我猜這是由於外部腳本是不是加載在蹲跳可以檢查 –