Home  >  Q&A  >  body text

Calling functions in dynamic HTML strings

<p>I have a structure in my application where I generate dynamic html. I add a html member to each user action that has a button. I want to assign my defined function to the (onclick) action of these buttons. However, when I click the button in the html string that I generate on the fly, I get an error that the relevant function is undefined. what do I do? My function;</p> <pre class="brush:php;toolbar:false;">returnButtonGroup(key: string):string{ return '<i onclick="testFunc('' key '');" class="fa fa-wrench"></i>' } testFunc(key:string){ console.log(key); }</pre> <p>I added the i tag by using innerHtml in every action of the user. Any suggestions on what I can do? Thanks. </p>
P粉132730839P粉132730839429 days ago490

reply all(1)I'll reply

  • P粉551084295

    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);
    }

    reply
    0
  • Cancelreply