2016-08-02 96 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

真棒它的工作 –