0

I am new to angular and trying to figure out a solution to this problem. In my .ts file I have string like var info = "Please Download File" + "<a (click)=downloadFile()>Click Here</a>. The anchor tag is dynamically added inside a function.I am trying to fire downloadFile() function but not sure how to solve this problem? When I inspect the element it does not show (click) function

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Rahul Kumar
  • 73
  • 1
  • 9
  • 1
    It's better to generate your html in the template, instead of in javascript. For example, you could have a `mylinks` array that contains all your urls, and then display that array in the template using `click me` as in this example: https://angular.io/guide/displaying-data – Kokodoko Dec 02 '19 at 21:41
  • Does this answer your question? [Angular HTML binding](https://stackoverflow.com/questions/31548311/angular-html-binding) – Heretic Monkey Dec 02 '19 at 22:00

1 Answers1

0

I agree with @Kokodoko that there is probably a better way to accomplish what you want. However, if you want to inject HTML you will need to Sanitize it and use innerHtml. For example in your typescript file you will need to do something like this:

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  constructor(protected _sanitizer: DomSanitizer) {}

  public info = "Please Download File" + "<a (click)=downloadFile()>Click Here</a>"


  safeHtml(html) {
    return this._sanitizer.bypassSecurityTrustHtml(html);
  }
}

and in your HTML

<div [innerHTML]="safeHtml(info)"></div>

I created a working StackBlitz that you can play with.

Narm
  • 10,677
  • 5
  • 41
  • 54
  • Thanks for your answer. I think i should have added more info on my question. info will be assigned to the property of custom element. For e.g the the already predefined custom element looks like: [message] [type] I was thinking of assigning info to message – Rahul Kumar Dec 02 '19 at 22:04
  • I added downloadFile() function to StackBlitz example but it's not doing anything. Can you suggest? – Rahul Kumar Dec 02 '19 at 22:24
  • That is a bit of a different conundrum indeed. Perhaps take a look at the accepted answer [here](https://stackoverflow.com/a/37676847/6335049). That may get you started down the right path. – Narm Dec 02 '19 at 22:50
  • Can you help me figuring out why downloadFile() function is not being called in StackBlitz example? – Rahul Kumar Dec 02 '19 at 23:28