【问题标题】:Angular2 pipes filter links in HTML stringAngular2管道过滤HTML字符串中的链接
【发布时间】:2016-08-02 22:07:54
【问题描述】:

由于我从外部源获取我的 HTML 字符串,我想过滤所有包含图像的链接,删除 href 属性并将其替换为(单击)事件...我正在尝试使用 angular 来执行此操作管道,管道只是删除了 href 属性,但点击事件不起作用

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

【问题讨论】:

  • 你可以试试:a.onclick = () => this.showLightbox;

标签: angular


【解决方案1】:

你可以试试这样的:

@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

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2015-07-14
    • 1970-01-01
    相关资源
    最近更新 更多