Angular 2 : dynamically making parts of a text clickable

标签 angular typescript

我有一个带有主题标签的文本。我想让这些标签可点击。 我创建了一个管道,它将用 cssClass hashTag 标记所有标签。现在我需要处理这些标签上的点击事件

这是一个示例代码

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {eigonic} from './hashtag'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 [innerHtml]="txt|hash"></h2>

    </div>
  `,
  pipes:[eigonic.Hashtag],
})
export class App {
  constructor() {
    this.txt = 'This is a #simple post on #Angular !'
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ],
})
export class AppModule {}

这是管道

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

export module eigonic {
    @Pipe({ name: 'hash' })
    export class Hashtag {    
        transform(value: string): string {
            return value == undefined ? value : value.replace(new RegExp('(#[A-Za-z0-9-_]+)', 'g'), '<span btn clear class="hashTag" >$1</span>'); 
        }

    }
}

还有一个 plunkr,以防你想玩玩。

https://plnkr.co/edit/vT1MrJNsupkBrhIMQ6qv

最佳答案

您可以使用 HostListener 来实现此目的,如下所示:

@HostListener('click', ['$event'])
onClick(e) {
  if (e.target.classList.contains('hashTag')) {
    alert('HashTag!');
  }
}

这是您的 fork 和更新的 plunk 查看src/app.ts。 有关 HostListener 的更多信息,请参阅 docs

关于 Angular 2 : dynamically making parts of a text clickable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39051150/

相关文章:

angular - 在模板中使用 Observable

angular - 无法从 ngrx/store 取消订阅 ActionsSubject

html - 如何使表格行在 Angular 2 中充当超链接

Typescript - 修改 lib.d.ts

Typescript 通过 in 运算符进行类型保护

typescript - 为什么 TypeScript 不强制执行接口(interface)签名?

javascript - 如何获得具有固定总和和大小的随机数列表

javascript - 如何在 Angular 4 中执行 onkeypress

node.js - 由于 Node.js 和 Angular 运行在不同的本地主机上,如何在 Angular 中使用 Nodemailer 电子邮件验证的路由?

TypeScript:无法识别 ES2015 字符串属性 'repeat'