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

Viewed 40

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

1 Answers

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

Related