将[innerhtml]中的(点击)与角(离子)绑定,以提及@或#标签

时间:2018-09-16 15:08:37

标签: javascript angular ionic-framework

您好,尝试动态地添加到用户提交的文本的某些部分的链接:

  submitText = '#test @mention http://google.com'

呈现html:

[innerHTML]="submitText | dynamiccontent"

但是渲染后的结果是: #test @mention http://google.com 但是(click)=“ goToPost($ 2)” 是打印的,不是按角度处理的。

<span class="font-bold" (click)="goToPost(test)">#test</span>

目标是:   如果#找到(click)=“ goToPost($ 2)” 如果@找到(click)=“ goToProfile($ 2)”

这是管道dynamiccontent.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';

@Pipe({ name: 'dynamiccontent' })

export class DynamicContentPipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {}

    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) {
        return this.sanitizer.bypassSecurityTrustHtml(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 class=\"font-bold noline\" href=\"" + url + "\" target=\"_blank\">" + url + "</a>";
                });
        }

        // Find/Replace @Handle/Mentions in text
        if (text.match(this.hashtags)) {
            text = text.replace(this.hashtags, "<span class=\"font-bold \" (click)=\"goToPost($2)\">$1$2</span>");
        }

        // Find/Replace #hashtags in text
        if (text.match(this.mentions)) {
            text = text.replace(this.mentions, "<a class=\"font-bold noline\" href=\"/search/handle/$2\" >$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;
    }  
}

0 个答案:

没有答案