2016-08-02 49 views
1

因为我从外部源获取我的HTML字符串,我想过滤所有包含图像的链接,删除href属性并用(单击)事件替换它...我是试图用一个角管要做到这一点,管只取出href属性,但单击事件不工作Angular2管道过滤HTML链接中的链接

我试过a.onclick = this.showLightbox;, 我试图a.addEventListener("click", this.showLightbox, false);

但都没有奏效

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

@Pipe({name: 'lightboxPipe'}) 
export class LightboxPipe implements PipeTransform { 

    transform(value: string): string { 

    let div = document.createElement('div'); 
    div.innerHTML = value; 

    [].forEach.call(div.getElementsByTagName("img"), (img) => { 
     var a = img.parentElement; 
     a.removeAttribute('href'); 
     a.onclick = this.showLightbox; 
    }); 

    return div.innerHTML; 
    } 

    showLightbox(){ 
    console.log('a link has been clicked'); 
    } 
} 
+0

你可以试试:'a.onclick =()=> this.showLightbox;' – rinukkusu

回答

0

你可以尝试这样的事情:

@Pipe({name: 'lightboxPipe'}) 
export class LightboxPipe implements PipeTransform { 

    transform(value: string, el): string { 
    let div = document.createElement('div'); 
    div.innerHTML = value; 

    [].forEach.call(div.getElementsByTagName("img"), (img) => { 
     var a = img.parentElement; 
     a.removeAttribute('href'); 
     a.onclick =() => this.showLightbox(img.src); 
    }); 

    el.appendChild(div); 
    } 

    showLightbox(src){ 
    console.log('a link has been clicked'); 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template: `<div #el>{{ html | lightboxPipe: el }}</div>`, 
    pipes: [LightboxPipe] 
}) 
export class App { 
    html = '<a href="#"><img src="http://placehold.it/350x150"></a>'; 
} 

Plunker Example

+0

真棒它的工作 –