P粉5510842952023-08-18 09:45:50
It is important to consider the scope and context of bound functions.
In your case, the testFunc function is defined in your Angular component, but it is called from the inline onclick attribute in the generated HTML string. This can cause scope and context issues.
In order to correctly bind events and functions in dynamically generated HTML in Angular, you should use Angular's event binding mechanism.
Update your returnButtonGroup function to return Angular template code instead of raw HTML string. Use Angular's (click) event binding to bind the testFunc function.
returnButtonGroup(key: string): string { return `<i (click)="testFunc('${key}')" class="fa fa-wrench"></i>`; }
Use
in HTML<div [innerHTML]="dynamicHtml"></div>
In your component.ts, create a property to hold the dynamically generated HTML, and make sure the testFunc function is accessible within the component.
dynamicHtml: string; constructor() { this.dynamicHtml = this.returnButtonGroup('someKey'); // 使用适当的键调用你的方法 } testFunc(key: string) { console.log(key); }