Instructions on enabling Angular 2 to detect dynamically added routerLink directive

As illustrated in this Plunker, I am dynamically injecting HTML into one of my elements, which can be simplified as follows:

@Component({
    selector: 'my-comp',
    template: `<span [innerHTML]="link"></span>`,
}) export class MyComponent {
    private linkContent = '<a routerLink="/my-route">GoTo Route</a>';
    private link;

    constructor(sanitizer: DomSanitizer) {
        this.link = sanitizer.bypassSecurityTrustHtml(linkContent);
    }
}

This leads to

<a routerLink="/my-route">GoTo Route</a>
being inserted into the DOM. However, Angular is unaware of the routerLink directive on this element, resulting in a lack of "binding." Consequently, clicking the link triggers a complete reload with re-bootstrap (which does not function properly in Plunk, displaying a 404 error).

Inquiry: How can we instruct Angular to traverse the DOM (or its specific parts, or even individual elements) and execute component initialization whenever necessary?

Answer №1

When dynamically adding HTML in Angular2, the framework does not process it in any way other than sanitization.

If you pass '

'<a routerLink="/my-route">GoTo Route</a>'
' to the innerHTML, it simply passes this string to the DOM without instantiating or applying the routerLink directive.

To add dynamic HTML that includes Angular2 bindings, directives, or components, you should add the HTML to a component's template and then dynamically add this component using

ViewContainerRef.createComponent()
. This technique is demonstrated in examples like Angular 2 dynamic tabs with user-click chosen components

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

Unable to retrieve environment values for Angular application in AKS

Our Angular application utilizes i18n and we are in the process of deploying it on Kubernetes. To ensure that we can build once and deploy to multiple environments, I referenced this resource for configuration guidance. I have set up env.js and env.templ ...

Angular - Execute function every 30 seconds while considering the duration of the function execution

In my Angular 7 application, I am utilizing RxJS to handle asynchronous operations. My goal is to retrieve a list of items from an API endpoint every 30 seconds. However, there are times when the request may take longer than expected, and I want to ensure ...

Enable the use of unfamiliar techniques on object

I am facing a challenge with an object that contains multiple method names which are not known at compile time. The signature of these methods always remains the same, but I am unsure about how to handle this scenario. I attempted to utilize an index type ...

Filtering strings with the same suffix

Here is a code snippet I am working with: type RouterQuery = keyof AppRouter['_def']['queries']; This code defines the following type: type RouterQuery = "healthz" | "post.all" | "post.byId" | "catego ...

Switch from flexbox layout to begin on the next column within the same row

I am attempting to create a CSS layout where, after a specific element like :nth-child(6), the elements will break and form a separate column within the same row. The parent element should split into 2 columns after every 6th element in the same row, then ...

Utilizing Angular 2's ViewChild within the <router-outlet> Tag

I've been working on a project using Angular 2. Within the MainComponent, I'm utilizing @ViewChild to reference child components. The MainComponent also contains a <router-outlet> where various components are loaded. My query is, how can I ...

The unique Angular type cannot be assigned to the NgIterable type

As a newcomer to Angular, I was introduced to types and interfaces today. Excited to apply my new knowledge, I decided to enhance my code by utilizing a custom interface instead of a direct type declaration: @Input() imageWidgets: ImageWidget; Here is the ...

Creating TypeScript domain objects from JSON data received from a server within an Angular app

I am facing a common challenge in Angular / Typescript / JavaScript. I have created a simple class with fields and methods: class Rectangle { width: number; height: number; area(): number { return this.width * this.height; } } Next, I have a ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

Combining ngModel and ngClass in Angular: a comprehensive guide

I have implemented the following code in Angular 6 using Visual Studio Code <div [ngClass]="{'disabled': isReadOnly}"> <label class="switch"> <input type="checkbox" name="Gender" ...

Utilizing nested observables for advanced data handling

Consider the following method: public login(data:any): Observable<any> { this.http.get('https://api.myapp.com/csrf-cookie').subscribe(() => { return this.http.post('https://api.myapp.com/login', data); }); } I want to ...

Searching and adding new elements to a sorted array of objects using binary insertion algorithm

I'm currently working on implementing a method to insert an object into a sorted array using binary search to determine the correct index for the new object. You can view the code on codesanbox The array I have is sorted using the following comparis ...

Unleash the power of Typescript and Node to create detailed REST API documentation!

Is it possible to generate REST API documentation using https://github.com/TypeStrong/typedoc similar to what can be done with ? I would appreciate any recommendations on leveraging TypeScript types for creating REST API documentation (specifically within ...

Issue with Nuxt: Property accessed during rendering without being defined on the instance

As I attempt to create cards for my blog posts, I encountered an issue with a Post component in my code. The cards are displaying like shown in the picture, but without any text. How do I insert text into these cards? Currently, all the text is within attr ...

An error has occurred: (SystemJS) A request error (404 Not Found) occurred while trying to load ng2-gridstack

I'm having some trouble installing the ng2-gridstack module on my Angular2 application. After a fresh installation, I ran: npm install gridstack (dependency) npm install ng2-gridstack I've been following the instructions, but unfortunately, I e ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

In the Vercel production environment, when building Next.js getStaticPaths with URL parameters, the slashes are represented as %

I've encountered an issue while implementing a nextjs dynamic route for my static documentation page. Everything works perfectly in my local environment, and the code compiles successfully. However, when I try to access the production URL, it doesn&ap ...

Why is Vite's hot reloading feature displaying unpredictable outcomes?

I have a unique setup consisting of Vite, Typescript, and Vue 3 SPA utilizing "script setup". This app is equipped with Urql to query data from a GraphQL endpoint. An interesting occurrence happens where the query results are only displayed after the comp ...

Tips for transferring JSON data into an array in Angular

How can I pass JSON data retrieved from an API into an array and then display that information in my template? I'm not sure how to accomplish this task. An error is appearing on my console, you can view it here. This is my TypeScript file: this.api. ...