0

I have an app in which I should get a dynamic text replace all occurrences of a string with a specific tag and then add a click listener to this tag so I can apply a new style to the tag.

I tried with jQuery, but it doesn't apply the listener, here's my component, any ideas?

template:
<div class="text-wrapper" [innerHTML]="text"></div>


export class FinderPage implements OnInit{

  chosedLetter: string = 'i';
  text = 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?';

  constructor() {}

  ngOnInit(){
    let regex = new RegExp(this.chosedLetter, 'g');

    this.text = this.text.replace(regex, `<span class="chosen-letter">${this.chosedLetter}</span>`);

    setTimeout(() => { //desperate measure with settimeout... :/
      
      $( ".chosen-letter" ).click(function(event) {
        event.stopPropagation();
        event.stopImmediatePropagation();
        $( this ).toggleClass('marked');
        alert('aaa')
      });
    }, 100);
  }

}
1
  • 1
    You should really not use jQuery here.. Use Angular. Commented Mar 14, 2020 at 23:49

1 Answer 1

1

Take a look at this StackBlitz project. I think it does what you're trying to do.

This code is pretty much this:

@Component({
  selector: "my-app",
  template: '<div class="text-wrapper" [innerHTML]="text"></div>',
})
export class AppComponent implements OnInit, AfterViewInit {
  chosedLetter: string = 'm'; // 'm' is easier to click than 'i'!
  text: string | SafeHtml = 'A very long string.';

  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2,
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit() {
    const regex = new RegExp(this.chosedLetter, 'g');
    const span = `<span class="chosen-letter")">${this.chosedLetter}</span>`;
    const plainText = this.text as string;
    const newText = plainText.replace(regex, span);
    this.text = this.sanitizer.bypassSecurityTrustHtml(newText);
  }

  ngAfterViewInit() {
    const elements = this.elementRef.nativeElement.querySelectorAll('.chosen-letter');
    elements.forEach(element => {
      this.renderer.listen(element, 'click', event => {
        element.classList.toggle('marked');
        console.log('Clicked on ' + this.chosedLetter);
      });
    });
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.