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

156
Views
Cómo activar el método al hacer clic en un enlace personalizado en angular 8

Tengo un escenario en el que necesito crear una etiqueta desde TS y necesito capturar el evento de clic si alguien hace clic en la etiqueta.

en html

 <p [innerHtml]="textField"></p> <button (click)="generateLink()">click</button>

En T

 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') }

Aquí, cada vez que haga clic en mí, haga clic en Necesito activar el método de actualización. enlace al enlace de stackblitz

Por favor, alguien que me diga cómo lograrlo. Gracias.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Parece que en este caso usar *ngIf sería la idea correcta para usar aquí. En angular, no compila HTML sobre la marcha, como solía hacer angularjs usando $compile API.

Lo que quiero decir es que la etiqueta innerHTML solo hará el trabajo de representar el HTML dentro del DOM, no habilitará ningún enlace allí (no puede llamar al método de update allí). Por lo tanto, puede usar la directiva *ngIf para mostrar y ocultar DOM condicionalmente.

 <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; }

Stackblitz bifurcado


Una forma alternativa de generar un enlace sin usar *ngIf es usar una combinación de ng-template y ng-container para generar e inyectar la plantilla manualmente.

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); }

Otro Stackblitz Bifurcado

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!