ngclass is not functioning properly when used with dynamically generated components

I am experiencing an issue with the components I create using createComponent. Although some of them function properly, others lack the appropriate CSS classes. Despite using a function and [ngClass] to set the classes, they do not appear when inspected in the DOM.

constructor (private injector: EnvironmentInjector) {};
const compRef = createComponent(RadioButtonComponent, { environmentInjector: this.injector});
document.body.appendChild(compRef.location.nativeElement);

The code for the radio button is found in radio.component.html

<div [ngClass]="classes">
...
</div>

Additionally, here is the code from radio.component.ts:

public get classes(): string[] {
let cls: string[] = [];
cls.push('some-class-name');
return cls;
}

Answer №1

Your classes may not be rendering because the component is being injected into the DOM but not into the Angular DOM. This means that Angular is unaware of your created component and does not trigger the get classes() method.

Instead of using document.body.appendChild, you should utilize Renderer2 and call its appendChild method instead.

constructor(
    private renderer2: Renderer2,
    private injector: EnvironmentInjector
    ) {}
...
const compRef = createComponent(RadioButtonComponent, { environmentInjector: this.injector});
this.renderer2.appendChild(THE_PARENT_ELEMENT, compRef.location.nativeElement);

THE_PARENT_ELEMENT acts as elementRef.nativeElement in this context.

Answer №2

If you want Angular to run change detection on your custom component, you need to connect it to the application following the instructions here in the documentation.

One way to do this is by injecting ApplicationRef into your constructor and utilizing it in the following manner:

constructor (private envInjector: EnvironmentInjector, private appRef: ApplicationRef) {};
    
const componentRef = createComponent(RadioButtonComponent, { environmentInjector: this.envInjector});
appRef.attachView(componentRef.hostView); // don't forget this line

document.body.appendChild(componentRef.location.nativeElement);

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

Changing the name of an Angular2 import module

Deciding to improve readability, I opted to rename the @angular module to angular2 and gain a better understanding of how imports function. Prior to making this change, the systemjs.config.js appeared like so: (function(global) { var map = { ...

Guide to automatically blur the input field and toggle it upon clicking the checkbox using Angular

<input (click)="check()" class="checkbox" type="checkbox"> <input [(ngModel)]="second_month" value="2019-09" type="month" [class.blurred]="isBlurred">> I need the second input(type=month) field to be initially blurred, and only unblur ...

Creating components with the viewContainerRef in Angular2 is functioning as expected

When attempting to load a dynamic component into the root component using viewContainerRef.createComponent, I encountered an issue where it appended to the wrong place. https://i.stack.imgur.com/lF1yT.png Here is my code: -----app.compoment.ts----- exp ...

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

Exploring ways to interact with an API using arrays through interfaces in Angular CLI

I am currently utilizing Angular 7 and I have a REST API that provides the following data: {"Plate":"MIN123","Certifications":[{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"preventive","StartDate":"06 ...

Angular enables the use of multiple instances of a service from the parent component to the child component

I recently came across this discussion: Utilizing multiple instances of the same service. Can one utilize multiple instances of a service from parent to children? For instance, imagine having an ElementService in the ParentComponent with 2 separate instan ...

Developing applications with Angular 4 and AppInventor window

Currently, I have a local Angular 4 application that utilizes localStorage on a desktop browser for data persistence. Within the application, I have implemented a WebViewer in AI. It is clear that localStorage cannot function in AI2, so alternative data s ...

Angular 2 is encountering issues with reading and displaying unicode characters (ud83dude31 or u0C28u0C3E) from the http response onto the user

My current task involves extracting unicode data from an http response, specifically for emojis. The response is in the form of a property-value pair within an object, with the message content being presented as JSON data ("messageContent":"hello \&bs ...

Exploring the functionality of Material components within a nested child component

I am facing an issue with my TestComponent, which uses a <mat-stepper> in its template. Due to the specific context of the stepper, I have to programmatically move to the next step instead of using the matStepperNext directive on a button. Here is a ...

How to access data within nested objects using ngFor in Ionic 4

How can I access the data I need from an API when it is nested within multiple objects? I am attempting to retrieve the full_url from the data object, which is nested inside the avatar object. I have already attempted the following: <ion-list> ...

The creation of an Outlook 365 add-in using Angular8 presents challenges when attempting to delete a cookie that was generated with ngx

I have developed an Office 365 add-in for Outlook. The add-in is built using Angular8 and I am utilizing ngx-cookie-service to store my authentication token information in a cookie. Despite being able to install the add-in, store the auth token in the co ...

Refreshing Angular 4 route upon modification of path parameter

I have been struggling to make the subscribe function for the params observable work in my Angular project. While I have successfully implemented router.events, I can't seem to get the subscription for params observable working. Can anyone point out w ...

Using NgRx to observe state changes in a service instead of relying on an Effect

Is it possible for a service to monitor state changes and make HTTP calls based on the state value without being triggered by an effect (NgRx)? In other words, can a service react to a portion of the store and eliminate the need for an effect to be involve ...

Utilize swipe gestures in tables with Angular and Ionic for enhanced user interaction

I'm working on creating a swiping functionality for table pagination. Swiping right will take you to the next page, while swiping left will move you back to the previous page. Here's the code snippet of my table: <table #tableElement id=&qu ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

Using the RxJS iif operator for implementing multiple condition statements

What is the optimal approach for returning Observables based on multiple conditions? This is my current code implementation: iif( () => !this.id, this.service.listStuff$(), this.service.listStuffById$(this.id) ).pipe( switchMap((list: L ...

What is the best way to disable a submit button based on form validity in Angular 4 with ng-content?

Include a form component that consists of an email field, password field, and submit button passed through ng-content. This allows the login form to display a 'Login' button and the register form to display a 'Register' button. Here is ...

Angular 5: Display a blank URL with the source until the variables are resolved

In my template, if I have: <img src="/somepath/{{user?.UserGuid}}.png" /> When user is not yet resolved, the ?. prevents evaluating UserGuid, resulting in: <img src="/somepath/.png" /> Is there a way to prevent this without using *ngIf or c ...

Unit Testing Angular: Passing FormGroupDirective into a Function

I am currently writing unit tests for a function that takes a parameter of type FormGroupDirective. I have been able to test most of the logic, but I'm unsure about what to pass as a parameter when calling the resetForm() function. Here is the code sn ...

The process of subscribing to a service in Angular

I currently have 3 objects: - The initial component - A connection service - The secondary component When the initial component is folded/expanded, it should trigger the expansion/folding of the secondary component through the service. Within the service ...