Angular2:动态地使文本的一部分可点击 [英] Angular2: dynamically making parts of a text clickable
本文介绍了Angular2:动态地使文本的一部分可点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有井号的文本.我想使这些标签可点击. 我创建了一个管道,该管道将使用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>');
}
}
}
和一个小矮人,以备不时之需.
https://plnkr.co/edit/vT1MrJNsupkBrhIMQ6qv
解决方案
您可以为此目的使用HostListener,例如:
@HostListener('click', ['$event'])
onClick(e) {
if (e.target.classList.contains('hashTag')) {
alert('HashTag!');
}
}
这是您的分叉版和更新版插件
检出src/app.ts
.
文档
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'
@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 {}
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.
https://plnkr.co/edit/vT1MrJNsupkBrhIMQ6qv
解决方案
You may use HostListener for this purpose like this:
@HostListener('click', ['$event'])
onClick(e) {
if (e.target.classList.contains('hashTag')) {
alert('HashTag!');
}
}
Here's your forked and updated plunk
Check out src/app.ts
.
More on HostListener in the docs
这篇关于Angular2:动态地使文本的一部分可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文