Amr ElAdawy Amr ElAdawy - 6 months ago 46
TypeScript Question

Angular2: dynamically making parts of a text clickable

I have a text with hashtags inside. I want to make these tags clickable.
I created a pipe that will mark all tags with cssClass hashTag. Now I need to handle click events on these tags

Here is a sample code

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

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

export class App {
constructor() {
this.txt = 'This is a #simple post on #Angular !'

imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ],
export class AppModule {}

and here is the pipe

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>');


and a plunkr in case you want to play around.


You may use HostListener for this purpose like this:

@HostListener('click', ['$event'])
onClick(e) {
  if ('hashTag')) {

Here's your forked and updated plunk Check out src/app.ts. More on HostListener in the docs