简体   繁体   English

如何使用innerHtml中的变量调用function?

[英]How to call the function with variable in innerHtml?

I've found example of calling function in innerHtml https://stackblitz.com/edit/angular-innerhtml-examples , but I don't know what to do, if function needs variable, which acceptable only from controller: I've found example of calling function in innerHtml https://stackblitz.com/edit/angular-innerhtml-examples , but I don't know what to do, if function needs variable, which acceptable only from controller:

 constructor(private elementRef: ElementRef, private sanitizer: DomSanitizer) {
    const currentString = "green";
    this.content = this.sanitizer.bypassSecurityTrustHtml(
      '<button type="button" id="submitButton" (click)="openWindow()">Submit</buttn>'
    );
  }
  openWindow(string) {
    alert(string);
  }

Try to add your variable as a param to addEventListener('click',someEventHander.bind(this, param1)) .尝试将您的变量作为参数添加到addEventListener('click',someEventHander.bind(this, param1))

Check this stackblitz example: https://stackblitz.com/edit/angular-innerhtml-examples-hdw7xs?file=src%2Fapp%2Fapp.component.ts检查这个 stackblitz 示例: https://stackblitz.com/edit/angular-innerhtml-examples-hdw7xs?file=src%2Fapp%2Fapp.component.ts

You can also refer to: https://www.codegrepper.com/code-examples/javascript/addeventlistener+with+arguments+in+angular+8也可以参考: https://www.codegrepper.com/code-examples/javascript/addeventlistener+with+arguments+in+angular+8

Also it is better/clean way to use bypassSecurityTrustHtml into angular pipe then call it from [innerHtml] .此外,使用bypassSecurityTrustHtml进入 angular pipe 然后从[innerHtml]调用它是更好/更干净的方法。 I adapted the above stackblitz example to use this way.我改编了上面的 stackblitz 示例以使用这种方式。

And finally, please use console.log() instead of alert() when debugging an application.最后,请在调试应用程序时使用 console.log() 而不是 alert()。 for reason and more details: Why is console.log() considered better than alert()?原因和更多细节: 为什么console.log()被认为比alert()更好?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM