Clickable elements in text


#1

Hi,

I’d like to know how to make elements in a text clickable. The text is user generated content which gets enhanced by a pipe which looks for specific patterns in the text and surrounds them with a which applies some styling to this pattern.
Now I’d like to present an ActionSheet when the user clicks such element. How can I achieve this, since its not part of the template at compile time?

Thanks for response!

Greetings
Ralf


#2

In case this turns out to be much more difficult than you might initially think, you could try this approach.


#3

Hi,
thanks for your fast response!

I think I got the idea, so I break the text up into “marked” and “text” parts, store them as array and use some switch to display it as text or special marked element. Thats a clever idea and will surely work, I think I’ll give it a try.

Thanks!

Greetings


#4

Works like a charm :blush:
For completeness, here an example of how I implemented it, in case others need it too:

I replaced the normal text binding with

<ng-container *ngFor="let component of item.description | richTextComponents">
	<tag *ngIf="component.type === 'tag'" [tag]="component.content"></tag>
	<ng-container *ngIf="component.type === 'text'">{{component.content}}</ng-container>
</ng-container>

And added this pipe as a test (in this case extracting something like hashtag syntax):

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
	name: 'richTextComponents'
})
export class RichTextComponents implements PipeTransform {
	transform(value: string, ...args: any[]): any {
		return value
			.split(/([#][A-Za-z0-9-_]{3,})/)
			.map((val: string) => {
				return {
					type: (val.startsWith('#') && val.length > 3) ? 'tag' : 'text',
					content: val
				}
			});
	}
}

The tag component is now able to handle the click event and open an ActionSheet.


How to create dynamic template to compile dynamic component?