【问题标题】:how to bind click event from ts to html dynamically to anchor tag using inner html in angular 7?如何在 Angular 7 中使用内部 html 将点击事件从 ts 动态绑定到 html 以锚定标签?
【发布时间】:2020-01-21 14:33:19
【问题描述】:

我想将 ts 到 html 的点击事件动态绑定到锚标记。
ts文件:

 this.RecommendedTests.Description = '<a (click)="showModel()">' 
  +this.RecommendedTests[i].Description + '</a>';

html:

 <div  [innerHTML]="RecommendedTests.Description"></div>

通过上面的代码sn-p,我可以得到锚标签,但是点击事件没有被触发。我认为是因为 XSS 清理问题,但是没有与 XSS 清理相关的适当解决方案,并且可以找到绑定点击事件。

如果我使用 DataSanitization 来绑定这些东西,是否会出现任何安全问题?

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: html angular dynamic anchor sanitization


    【解决方案1】:

    试试这样:

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

    导出类 AppComponent {

      constructor(private sanitizer: DomSanitizer) {
    
        Window["AppComponent"] = this;
      }
    
    
      this.RecommendedTests.Description = this.sanitizer.bypassSecurityTrustHtml('<a onClick="Window.AppComponent.showModel()">'
          + this.RecommendedTests[i].Description  + '</a>')
    
    
      showModel() {
        alert("ok")
      }
    }
    

    Working Demo

    【讨论】:

    • @adrita.Thanks..但我尝试了这个解决方案,但没有奏效。由此形成的锚标记,但点击事件仍然丢失。
    • @Mr.Roshan 做了一些更改并添加了演示。请检查
    • 用onClick替换(点击)
    • 谢谢。我得到 SafeValue must use [property]=binding: error on my Front end。
    • 你能重新创建问题并分享stackbiltz
    【解决方案2】:

    this.RecommendedTests.Description = <a (click)="showModel()"> +this.RecommendedTests[i].Description + </a> ; 在你的代码中试试这个,我认为它是工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 2021-09-03
      • 2015-10-12
      • 2015-08-24
      • 1970-01-01
      相关资源
      最近更新 更多