【问题标题】:Angular2: dynamically making parts of a text clickableAngular2:动态地使部分文本可点击
【发布时间】:2016-08-20 18:58:15
【问题描述】:

我有一个带有主题标签的文本。我想让这些标签可点击。 我创建了一个管道,它将用 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

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以像这样使用 HostListener:

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

    这是您的分叉和更新plunk 查看src/app.ts。 在docs 中了解更多关于 HostListener 的信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-28
      • 2016-12-10
      • 1970-01-01
      • 2023-03-22
      • 2012-01-01
      • 2012-05-28
      • 2020-05-08
      相关资源
      最近更新 更多