Angular2管道过滤HTML字符串中的链接

时间:2016-08-02 13:17:10

标签: angular

由于我从外部源获取HTML字符串,我想过滤包含图像的所有链接,删除href属性并将其替换为(click)事件...我试图用角度来做这个管道,管道只删除href属性,但click事件不起作用

我试过了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'); } }

但两者都不起作用

    -dontwarn retrofit.**
    -keep class retrofit.** { *; }
    -keepattributes Signature
    -keepattributes Exceptions
    -dontwarn java.lang.invoke.*
    -keep class com.elephantmobile.ui.remote.model.** { *; }
    -dontwarn retrofit.appengine.UrlFetchClient
    -keepclasseswithmembers class * {
        @retrofit.http.* <methods>;
    }
    -keepclassmembernames interface * {
        @retrofit.http.* <methods>;
    }
    -dontwarn retrofit2.Platform$Java8

1 个答案:

答案 0 :(得分: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

相关问题