Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
How to trigger the method on click of custom link in angular 8

I have a scenario where I need to create a tag from TS and i need to capture the click event if someone click on tag

In Html

<p [innerHtml]="textField"></p>

<button (click)="generateLink()">click</button>

In Ts

textField = 'Hello click button for link';

  generateLink() {
    this.textField = `${this.textField} <a href="#" onclick="update()">click me</a>`;
  }

  update(){
    console.log('click me is clicked')
  }

Here whenever click me is click I need to trigger update method. link to stackblitz link

Please anyone let me know how to achieve it.Thanks

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

It feels that in this case using *ngIf would be the right idea to use here. In angular it does not compile HTML on the fly, like how angularjs used to do using $compile API.

What I mean is innerHTML tag will just do the work of rendering the HTML inside DOM, it won't enable any binding there (you can not call update method there). Hence you can use *ngIf directive to show and hide DOM conditionally.

<ng-container *ngIf="showLink">
  {{textField}}
  <a href="#" (click)="update()">click me</a>
</ng-container>

<button (click)="generateLink()">click</button>

TS

  showLink = false;

  generateLink() {
    this.showLink = true;
  }

Forked Stackblitz


An alternative way to generate link without using *ngIf, is by using combination of ng-template and ng-container to generate and inject template manually.

HTML

<ng-container #links></ng-container>

<button (click)="generateLinkFromTemplate()">another click</button>

<ng-template #link>
  {{ textField }}
  <a href="#" (click)="update()">click me</a>
</ng-template>

TS

@ViewChild('links', { read: ViewContainerRef }) links: ViewContainerRef;
@ViewChild('link', { read: TemplateRef }) link: TemplateRef<any>;

generateLinkFromTemplate() {
  this.links.createEmbeddedView(this.link);
}

Another Forked Stackblitz

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!