我有一个带有主题标签的文本。我想让这些标签可点击。 我创建了一个管道,它将用 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,以防你想玩玩。
最佳答案
您可以使用 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/