Angular: Exploring the Dynamic Loading of a Component from a String Declaration

Is there a way to compile a component defined by a string and have it render in a template while still being able to bind the click event handler?

I attempted to use DomSanitizer:

this.sanitizer.bypassSecurityTrustHtml(parsedLinksString);

However, this approach did not properly bind the click event handler onButtonClick().

What I'm Trying To Achieve

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

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

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

}

Answer №1

The security model of Angular ensures that any HTML added using [innerHTML]="myOutput" is not processed, meaning scripts will not run and events will not be triggered.

When it comes to compiling HTML in Angular, there are several options available:

Adding HTML to a Component Template

If you want to include HTML dynamically in a template, you can place it in the sample-component.component.html file and utilize structural directives like *ngIf or *ngFor.

Creating a Dynamic Component to Load at Runtime

Check out the Dynamic Component Loader guide for more information.

View Stackblitz Demo

Answer №2

Summary: Click here

I had a similar query on Stack Overflow and found the resolution here provided by @cris hamilton.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extracting the base href in Angular 6

Is there a way to dynamically retrieve /CTX-ROOT/assets/tiny-editor/langs/cs.js in Angular 6 component without using the PlatformLocation#getBaseHrefFromDOM method? constructor( private zone: NgZone, private platformLocation: PlatformLocation) ...

Having trouble declaring a module in an npm package with Typescript?

I'm currently working on a project using Vue.js and TypeScript. Within project "A," I am utilizing a private npm package called "B," which serves as a component library. This package "B" also incorporates another library, 'tiptap,' which unf ...

Having trouble installing the Angular/CLI on macOS Mojave due to a node-pre-gyp error?

I recently formatted my iMac and deleted all files on the hard drive. However, upon installing Angular CLI 7, I encountered an error log message in the terminal console. Environment macOS: Mojave 10.14.2 node: v10.15 npm: 6.4.1 Console Error miguels- ...

Error: 'Target is not found' during React Joyride setup

I am attempting to utilize React Joyride on a webpage that includes a modal. The modal is supposed to appear during step 3, with step 4 displaying inside the modal. However, I am encountering an issue where I receive a warning message stating "Target not m ...

Challenges arise when working with Vue 3.2 using the <script setup> tag in conjunction with TypeScript type

Hey there! I've been working with the Vue 3.2 <script setup> tag along with TypeScript. In a simple scenario, I'm aiming to display a user ID in the template. Technically, my code is functioning correctly as it shows the user ID as expect ...

I'm having trouble establishing a connection with the Appwrite platform

Encountered an issue while trying to connect to appwrite. The specific error message is: Uncaught (in promise) TypeError: Failed to construct 'URL': Invalid URL at Account.<anonymous> (appwrite.js?v=d683b3eb:932:19) at Generator.nex ...

Craft dynamic SVG components using TypeScript

Looking to generate a correctly formatted SVG element using TypeScript: createSVGElement(tag) { return document.createElementNS("http://www.w3.org/2000/svg", tag); } Encountering an issue with tslint: Error message: 'Forbidden http url in str ...

Angular 2: A ready-made solution for developing interactive discussion features

Currently working on my Angular 2 application and looking to incorporate a discussion feature. Are there any pre-existing solutions available for this integration? ...

Updating a single record in Angular 9 using Angular Material's Mat table

I am facing a unique scenario and seeking assistance with the following issue. In my application, I utilize a mat table to display data which is constantly being updated through signalR from the backend. This frequent data updating poses a challenge for m ...

Vue3 and Ionic combined to create a Component that became a reactive object in Vue

Vue is issuing a warning about receiving a Component as a reactive object, which can cause unnecessary performance overhead. The warning suggests using markRaw or shallowRef instead of ref to avoid this issue. However, in my code, I am not explicitly using ...

Inject a new observable into the current Subject

Having an Angular Subject named event$, I want to attach DOM controls as emitters to this observable when screens are loaded. The observable already has subscribers, so I am using a method to merge another observable with it, as shown below (Subscription m ...

Travis build unsuccessful due to version inconsistencies

I am facing an issue where my locally working application is failing to build on TravisCI. After some research, I realized that I used "latest" as the version for dependencies in my package.json file. :rekolekcje-webapp:npmInstallnpm WARN deprecated <a ...

Transferring information from parent page to child page using Angular version 8.2.4

As a newcomer to Angular, I am facing a challenge in sharing data between pages upon loading the main page. The structure involves using dynamic forms to generate dynamic pages within the main page. However, when trying to pass data from the main page to t ...

Is it possible to verify if the @Output is correctly wired up within an Angular component?

When working with Angular and TypeScript, it is possible to access the bound @Input values in the ngOnInit method of a component. However, there isn't a straightforward way to check if a particular @Output event binding has been set up on the componen ...

Tips for refining TypeScript discriminated unions by using discriminators that are only partially known?

Currently in the process of developing a React hook to abstract state for different features sharing common function arguments, while also having specific feature-related arguments that should be required or disallowed based on the enabled features. The ho ...

Encountering issues with dependencies while updating React results in deployment failure for the React app

Ever since upgrading React to version 18, I've been encountering deployment issues. Despite following the documentation and scouring forums for solutions, I keep running into roadblocks with no success. The errors displayed are as follows: $ npm i np ...

My default value is being disregarded by the Angular FormGroup

I am facing an issue with my FormGroup in my form where it is not recognizing the standard values coming from my web api. It sets all the values to null unless I manually type something into the input field. This means that if I try to update a user, it en ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

Upgrading to TypeScript: How to resolve issues with const declarations causing errors in JavaScript style code?

Currently, I am in the process of migrating a decently sized project from JavaScript to TypeScript. My strategy involves renaming the .js files to .ts files, starting with smaller examples before tackling the larger codebase. The existing JavaScript code i ...

Can the type of a prop be specified in the parent component before it is passed down to the children components that utilize the same prop?

In my codebase, I have a component called NotFoundGuard. This component only renders its children if a certain condition is true. Otherwise, it displays a generic fallback component to prevent redundancy in our code. I am trying to figure out if there is ...