Setting an attribute on a custom component that is dynamically created within an Angular application

I am working with a custom library component called <my-icon>. To display the icon, I need to specify the property [name] like this:

<my-icon [name]='warning'></my-icon>

Currently, I am dynamically creating these icons in TypeScript:

if (myCondition) {
    let icon = <HTMLElement>document.createElement('my-icon');
}

How can I set the [name] property on my variable icon to achieve the same result as above? I have tried using

icon.setAttribute('name','warning')
, but it seems to only set the HTML attribute name rather than the input name of the Angular component underlying it.

Answer №1

document.create function is only capable of creating DOM elements, not Angular components. To dynamically create an Angular component, you will need to utilize the ComponentFactoryResolver service.

constructor(private componentResolver: ComponentFactoryResolver) { }

This service can be used as shown below:

// create factory for icon component
const factory = this.componentResolver.resolveComponentFactory(MyIconComponent);

// create icon component and append it next to anchor element
const icon = this.anchor.createComponent(factory);

// assign some value to component input
icon.instance.name = 'icon name';

The anchor element can be accessed using ViewChild. For example, if your component template includes:

`<div #iconsHere></div>`

You should add the following annotation:

@ViewChild('iconsHere', {read: ViewContainerRef}) anchor: ViewContainerRef;

Remember that dynamically created components must be declared as entry components in your module.

@NgModule({
  ...
  entryComponents: [ MyIconComponent ]
})
export class AppModule { }

Check out a live demo here: https://stackblitz.com/edit/angular-jukjib

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

When retrieving data from MongoDB, an error occurs stating "Unable to read the property 'firstname' of null."

I've been working on retrieving user information from MongoDB and displaying it through HTML, but I keep encountering an error that says: "Cannot read property 'firstname' of null." For my backend service, I'm using Express and Node.js, ...

Can a single data type be utilized in a function that has multiple parameters?

Suppose I have the following functions: add(x : number, y : number) subtract(x : number, y : number) Is there a way to simplify it like this? type common = x : number, y : number add<common>() This would prevent me from having to repeatedly define ...

Interactive feature on Google Maps information window allowing navigation to page's functions

Working on an Angular2 / Ionic 2 mobile App, I am utilizing the google maps JS API to display markers on a map. Upon clicking a marker, an information window pops up containing text and a button that triggers a function when clicked. If this function simpl ...

Combining a pair of canvases

Currently, I am utilizing a JavaScript library to create a QR Code. This library generates the QR code by displaying it on a canvas. Nevertheless, my goal is to integrate a background behind this QR Code. I attempted to achieve this by first drawing the b ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...

TypeScript is throwing an error about a missing property, even though it has been defined

Within the PianoMK1Props component, there is a prop known as recording which accepts an object with specific properties. The structure of this object is defined like so(the state variable): const [recording, setRecording] = useState({ mode: "REC ...

Tips on updating the content of an HTML element dynamically when it is already being populated using *ngFor

I have created an HTML component that utilizes *ngFor to dynamically generate HTML elements. This results in a total of 3 tags being generated when the code is run. I have included data such as subject in the component file which updates dynamically, how ...

Setting up Webhook for Clerk in a Next.js and Prisma (T3 stack) environment

I am facing a challenge in my personal project using Next.js (T3 stack) where I need to synchronize Clerk users with a user table in my Supabase DB. My goal is to have a Users table, defined in my schema.prisma, that includes the user_id from Clerk along ...

Using Angular's routerLinkActive to manage active states for multiple paths

With my Angular 5 project, I have successfully implemented a bootstrap nav-bar menu where routerLinkActive works perfectly when the initial path matches the routerlink of the menu item, like this: <li [routerLinkActive]="['active']"> < ...

How can the `ng new --collection` command be utilized in Angular?

Can you explain the purpose of using the ng new --collection command in Angular? And can you provide instructions on how to use it in the command prompt? If you have any knowledge about this, please share with me. ...

Accepting undefined in rest parameter of typescript

I'm struggling with an exercise involving Function parameters: The maximum function below has the wrong type. To allow undefined in the rest arguments, you need to update the type of the rest parameter. Fortunately, you don't have to change the ...

Struggling with implementing conditional validators in Angular2 form models. I have tried using myForm.setValidators(), but it doesn't appear to be functioning as expected

I have been experimenting with the model form in an Ionic/Angular2 project. My goal is to implement conditional validation on a form where users initially fill out 6 required fields, and then choose between 'manual' and 'automatic' proc ...

Can an IonChange event be triggered from a component in Ionic 3?

Currently, I am working on developing an application that involves multiple forms. In most instances, when a user navigates back from the Confirmation view to the Form view to modify their entered data, it is essential for the form to retain the previously ...

Page Breaks - Patience in anticipation of dataSource readiness

I am facing an issue with my pagination service and component. The dataSource appears empty when the page is loaded for the first time, but by the second time it is populated and I can display the dataTable and paginate successfully. Is there a workaround ...

Using Angular and RxJS5 to refresh data from both HTTP requests and sockets

Here's a specific scenario I need to address: Retrieve route parameters Utilize route parameters to make an HTTP service call Upon receiving a response from the HTTP service, use the same route parameters to invoke a socket service Whenever the sock ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

How can I load a separate component.html file using a component.ts file?

Hey there, I'm a beginner with Angular and I have a question about loading a different home.component.html file from a method within books.component.ts. Here's the code snippet from my books.component.ts file: import { Component, OnInit } from ...

Upon updating my Angular application from version 5.2 to the most recent one, I encountered an ERROR when running ng build

There was an error in the file ./src/styles.css (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./src/styles.css) The module build failed due to a SyntaxError (60: ...

In Angular, the data retrieved from the API will only appear on the page once it has been manually

Recently, I started working on an Angular project and encountered a problem with data display after each component routing. Initially, the data is not displayed until the page is reloaded. You can see the issue in the screenshots: [![After reload][2]][2]. ...

Guide to dynamically setting the index element with ngFor in Angular

When working with NgFor in Angular, I am interested in dynamically handling attributes using an index. I have a collection of properties/interfaces that look like this: vehicle1_Name, vehicle2_Name, vehicle3_Name vehicle4_Name, totalVehCount To achieve t ...