Home > Mobile >  HTML Button tags are ignored
HTML Button tags are ignored

Time:12-11

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 (click)="onHashtagClick($1)" >#$1</button>');
}

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

This results in the following description:

Listening to the rain, falling on the streets <button (click)="onHashtagClick(Rain)" >#Rain</button> <button (click)="onHashtagClick(Chill)" >#Chill</button>

But when I put it in my HTML, the element shows up like this: enter image description here

The HTML tags of the button are literally printed on the screen. I found that in Angular, I needed to use the [innerHTML] tag for this, so my HTML became:

<label  [innerHTML]="description"></label>

But that resulted in the original text without any HTML tags around the hashtags: enter image description here

How can I make buttons of the hashtags (no hyperlinks). Please let men know what I am doing wrong?!

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