我尝试呈现一个按钮,它可以正常工作,但是当我单击该按钮时,它不会执行alertWindow函数,帮助!:
app.component.ts:
import {
Component,
ElementRef,
OnInit,
ViewEncapsulation } from '@angular/core';
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.ShadowDom,
})
export class AppComponent implements OnInit {
public content: SafeHtml;
constructor(private sanitizer: DomSanitizer) {}
async ngOnInit() { this.renderButton(); }
alertWindow() { alert("don't work"); }
renderButton() {
this.content =
this.sanitizer.bypassSecurityTrustHtml(`
<button (click)='connectWallet()' class="button">
Connect your wallet
</button>`);
}app.component.ts;
<div [innerHTML]="content"></div>发布于 2022-06-24 16:36:06
解决方案
根据我的理解,您想在运行时动态显示HTML吗?然后,解决方案是使用ComponentFactoryResolver和ViewContainerRef
如果你能提供更多的细节,你想要达到的目标,这样人们就可以指导你,这样会更好。
为什么不起作用?
它不起作用,因为它超出了角度,当您使用innerHTML时,您传递给它的是纯香草HTML和JavaScript。
试试这个例子
(window as any).alertWindow = function () {
alert("don't works");
};
@Component({...})
export class AppComponent {
...
renderButton() {
this.content = this.sanitizer.bypassSecurityTrustHtml(`
<button onclick='alertWindow()' class="button">Connect your wallet</button>
`);
}
}它起作用了吗?
如您所见,我已将alrertWindow函数移出组件的类,并添加到window变量中,并将(click)更改为onclick
https://stackoverflow.com/questions/72746632
复制相似问题