0

i have this syntax on angular(typescript), my problem is when this code runs, its automatically runs clickShowAttachments function, instead i am need to run function when this button clicks ...

${data.attachments ? `<button (click)="${this.clickShowAttachments(data.attachments)}">show attachments</button>` : ''}

and when it compiles, if i inspect page i see that : (click)="undefined" (https://i.stack.imgur.com/6kEin.png)

i tried replace double quote with single quote but nothing happens ..

Amin Zekri
  • 21
  • 2

2 Answers2

2

I fixed it this way:

const a = `<button id="btn1">btn text</button>`;
document.getElementById("btn1").addEventListener('click', ()=> this.clickShowAttachments(data.attachments));
rlandster
  • 7,294
  • 14
  • 58
  • 96
Amin Zekri
  • 21
  • 2
1

You are getting undefined because this.clickShowAttachments(data.attachments) returns undefined.

have you tried using

${data.attachments ? `<button (click)="this.clickShowAttachments(data.attachments)">show attachments</button>` : ''}

You can do this in angular2+

<button *ngIf="data?.attachments" (click)="this.clickShowAttachments(data.attachments)">show attachments</button>
Prashant Singh
  • 611
  • 1
  • 5
  • 14
  • yes, its not runs the function .. – Amin Zekri Dec 21 '22 at 08:19
  • Can you share the code on https://stackblitz.com/ what exactly you are trying to achieve that might help in helping you. – Prashant Singh Dec 21 '22 at 08:22
  • i shared above, after that backtick string, i have a function "clickShowAttachment(attachments)" witch is responsible for showing my attachments. – Amin Zekri Dec 21 '22 at 08:35
  • I hope you are using angular 2+ then you can use *ngIf="someBooleanConditionOnIt" to show or hide element conditionally. I have updated my answer. – Prashant Singh Dec 21 '22 at 08:48
  • if i do this on html file, it will be okay, but i need to store this html in ts file with backtick, which is not diffrent and probelm still be there .. – Amin Zekri Dec 21 '22 at 09:00
  • You can do it but it will not work like this, you will need to use innerHtml and pass the html content then have to apply event listener to achieve what you want. – Prashant Singh Dec 21 '22 at 09:41