Home > Enterprise >  Typescript Make hashtag clickable with button
Typescript Make hashtag clickable with button

Time:12-10

I have a problem in my angular project. I have a raw text with hashtags, for example: Listening to the rain, falling on the streets #Rain #Chill

Now I want those 2 hashtags to be buttons, so I had this in my typescript:

ngOnInit(): void {
    this.description = this.description.replace(/#(\w )/g, '<button  onclick="onHashtagClick($1)">#$1</button>');
}

onHashtagClick(hashtag:string) {
    console.log(hashtag);
}

But this doesn't change the text at all, but when I change button to <a href> like this:

this.description = this.description.replace(/#(\w )/g, '<a href="" >#$1</a>');

The hashtags are hyperlinks...

The reason, I want a button is because to let the <a> tag work, I need to provide a href, but I don't want that. I want to call a function named onHashtagClick()....

Here is the HTML:

Why is the button not working for this?

CodePudding user response:

If you really need buttons I would create a button array and use ngFor to show the list of buttons.

First: Create an array of buttons

public buttons:Array<string> = [];

Second: Extract the buttons from string with regex match.

this.description.match(/#(\w )/g).forEach((e) => {
    buttons.push(e);
});

Third: Show buttons with *ngFor

<button *ngFor="let i of buttons" (click)="onHashtagClick(i)">{{i}}</button>

CodePudding user response:

When you created a button you need to use one-way binding syntax

instead of

<button  onclick="onHashtagClick($1)">#$1</button>

you write your click function like this:

'<button  (click)="onHashtagClick($1)">#$1</button>

Also where you say 'Here is the HTML:' there is nothing there.

  • Related