Apply dynamic directives to an HTML string fetched from the server

Receiving a string of HTML from the server with custom directive attributes that Angular should render, but struggling to make the directives work. Is it possible to load HTML containing custom directives?

I've been using DomSanitizer.bypassSecurityTrustHtml() method to render the markup correctly, but can't get the directives to run on the tags.

Here's an example of what I'm trying to achieve, server-side declared markup with client-side custom directives:

import {Component, Directive, ElementRef, Renderer} from "@angular/core"
import {DomSanitizer, SafeHtml} from "@angular/platform-browser"

@Component({
    selector: 'MyComponent',
    templateUrl: '<div [innerHTML]="myContent">',
})

export class MyComponent
{
    dynamicContent: SafeHtml;

    htmlFromTheServer: string = '<p>This is an input: </p><input type="text" custom>';

    constructor(private domSanitizer: DomSanitizer)
    {
    }

    ngOnInit()
    {
        this.dynamicContent = this.domSanitizer.bypassSecurityTrustHtml(this.htmlFromTheServer);
    }
}

@Directive({
    selector: '[custom]'
})
export class MyDirective
{
    constructor(public element: ElementRef,
                public renderer: Renderer)
    {
        renderer.setElementStyle(element.nativeElement, 'border', '1px solid red');
    }
}

If the directive is applied to the markup, it should have a red border around it, but I'm having trouble getting it to work.

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

Ensure that only one property is mandatory in a Typescript interface, while permitting the rest to be

In my project, I am developing a WebSocket component that requires the type Message to have a mandatory property named type. export type Message = { type: string; [key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any }; This c ...

What benefits does redux-thunk offer?

Why is redux-thunk necessary? It seems like using a thunk just adds an extra layer of complexity by wrapping expressions and using middleware. The sample code from redux-thunk further confuses the process. import thunk from 'redux-thunk'; // No ...

Error encountered while trying to update Angular: Unable to retrieve metadata for '@angular/core' due to an invalid URL: 127.0.0.1:4200

I encountered an error while attempting to update my Angular project from version 9.1 to 10, and the same issue arose when updating another project from Angular 10 to 11. https://i.sstatic.net/TISIX.png Has anyone else experienced this problem? What migh ...

Step-by-step guide on creating a spy() function

const spawnedComponent = MockComponent; it('verifies that the Component is invoked', () =\>{ spawnedComponent.yourComponent() // invoking the your component for the first time spyOn(spawnedComponent, 'method').and.returnValue ...

Angular 2 component stays static despite changes in route parameters

So, I am in need of a way to refresh my component after the URL parameter's id has been altered. The following code is from my player.component.ts: import {Component, OnInit, AfterViewInit} from '@angular/core'; import {ActivatedRoute, Rout ...

Error: No @Directive annotation was found on the ChartComponent for Highcharts in Angular 2

I'm having trouble integrating Highcharts for Angular 2 into my project. After adding the CHART_DIRECTIVES to the directives array in @Component, I encountered the following error in my browser console: EXCEPTION: Error: Uncaught (in promise): No ...

In TypeScript, Firestore withConverter may return a QueryDocumentSnapshot instead of the expected Class object

I'm currently exploring the usage of Firestore's withConverted method in Typescript to retrieve queries as instances of my customized class. Custom EventConverter Class import Event from "@/models/Event"; class EventConverter implemen ...

Angular Route Authorities is a powerful tool for managing permissions

In my routes, I have a specific path: {path: 'Demands/:id', component: EditDemandesComponent}. This path allows me to edit demands. However, I've noticed that if the ID does not belong to one of my demands, I am still able to access the path ...

When trying to create a new project using `ng new project`, the path specified was not

I'm attempting to start an angular 4 project using angular-cli on my Windows 10 operating system. I followed the instructions outlined at https://www.npmjs.com/package/@angular/cli. Currently, I am running node - 7.6.0 and npm - 5.1.0. Every time I ...

How to update a variable in the app.config.json file in Angular 5

I've created a custom asset JSON configuration file called .angular-cli.json to use as default. However, there are certain instances where I need to update specific values within this file but I'm not sure how to go about it. Any suggestions? .a ...

Which specific version of @angular/material should I be using?

After starting a new project, I encountered an issue while trying to install ng add @angular/material. The error message received was: # npm resolution error report While resolving: @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Getting the logged in user's ID in Angular using MongoDB and Node.js for the backend

How can I retrieve the logged user's ID so that when they click on "My profile", they are directed to url/profile/theirId? Thank you for your help! Below is my authentication.service code: export interface UserDetails{ username: string email: stri ...

Why aren't functions included when casting from a JSON literal to a specific type?

In my model class, the structure looks like this: export class Task { public name: string; public status: string = "todo"; public completeTask(): void { this.status = "done"; } } There is also a service responsible for retrie ...

What is the process for gaining entry to the environment files of a separate project?

I am working with two Angular projects. The first project is called Main, and I need to load environment files from the second project into Main. I understand that we can access assets/a.json in another project using HttpClient.get. Can someone please ad ...

Setting IDPs to an "enabled" state programmatically with AWS CDK is a powerful feature that allows for seamless management of

I have successfully set up Facebook and Google IDPs in my User Pool, but they remain in a 'disabled' state after running CDK deploy. I have to manually go into the UI and click on enabled for them to work as expected. How can I programmatically e ...

Failure in Testing: ReferenceError indicating that SpeechSynthesisUtterance has not been defined

In a recent project, I decided to add text-to-speech functionality and opted for a plain JavaScript solution. (https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance) Currently, I am using [email protected] and [email protecte ...

Fetching a collection from Cloud Firestore using Angular and Firebase

I'm looking to figure out how to retrieve lists from cloud firestore. Here is how I upload a list : export interface Data { name: string; address: string; address2: string; pscode: string; ccode: string; name2: string; } constructor(pri ...

"Encountering a 404 Not Found error while attempting to access Angular

Welcome to my index.html file! <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Discover AngularJS2</title> <!-- bootstrap --> ...

The error message "The property 'handleLoginDisplay' is not found in the type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'" is displayed

When I try to compile this TypeScript code, it throws an error. Can anyone help me understand why? import { connect } from 'react-redux'; import React from "react"; import { Link, Redirect } from "react-router-dom"; class HeaderComponent extend ...

How can I easily move from a shared page to a specific page in Angular 8?

Just stepping into the world of front-end development, I have a scenario where my menu page offers 3 options to navigate: Go to Arena. Go to Dungeon. Go to Battleground. However, clicking on any of these options leads me to a common page for character p ...