1

How do I compile a component defined by a string and render it in my template?

I tried using DomSanitizer:

this.sanitizer.bypassSecurityTrustHtml(parsedLinksString);

But that doesn't properly bind the click event handler onButtonClick().

Desired Functionality

@Component({
    selector: 'app-sample-component',
    templateUrl: './sample-component.component.html',
    styleUrls: ['./sample-component.component.scss']
})
export class SampleComponent {

  buildMessage() {
    // How do I parse this string and render so that it responds to events?
    const myOutput = '<button (click)="onButtonClick()';
  }

  onButtonClick() {
    console.log('Handler for Dynamic Button');
  }

}

5
  • are you using the innerHTML attribute on the parent DOM element to the rendered string? from here Commented Sep 24, 2019 at 20:45
  • This strikes me as an XY Problem. People may be able to better assist you if you ask about what outcome or functionality you are trying to obtain. What is the reason for trying to create a button like this via an HTML string? Commented Sep 24, 2019 at 22:10
  • Yes, I tried using the innerHtml attribute and render it, however (click) events does not work as it's pure HTML and does not understand Angular bindings. Commented Sep 25, 2019 at 21:08
  • How would you develop the following component? A Notification Component, that is connects to a store, and any component can call an action and displays notifications. However, these notification texts may contain a call to action link (like, click here for more). This link is a dynamic content and also have to bind to a method/event in an Angular class Commented Sep 25, 2019 at 21:09
  • If only want a button, check this SO Commented Mar 24, 2022 at 21:09

2 Answers 2

1

The Angular security model is designed such that HTML added to [innerHTML]="myOutput" is not processed (i.e. scripts are not executed and events are not triggered).

Angular options to compile HTML include:

Add HTML to a Component Template

In your example, the HTML would go in sample-component.component.html. To dynamically include or exclude HTML in a template, use structural directives such as *ngIf and *ngFor.

Create a Dynamic Component to load at Runtime

See Dynamic Component Loader

Stackblitz Demo

Sign up to request clarification or add additional context in comments.

Comments

0

TLDR: https://stackblitz.com/edit/angular-ivy-86uxvs?file=src/app/app.component.html

I did same question and the solution was here made by @cris hamilton.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.