Sharing Top Content from the Angular-sphere.

Dynamically Creating Components With Angular – Netanel Basal

Dynamically Creating Components With Angular

☞ 

#Angular #javascript

  • Note: The container can be any DOM element or component.
  • Now we need to get a reference to our template element in my-app component.
  • The default return from the ViewChild decorator is the component instance or the DOM element, but in our case, we need to get the element as ViewContainerRef .
  • ViewContainerRef stores a reference to the template element ( our container ) and also exposes an API to create components.
  • Internally this method will call the create() method from the factory and will append the component as a sibling to our container.

For the simplicity we are going to use a simple alert component that will take as Input the alert type. Next, If you think about it, eventually components are actually DOM elements so if you need to…

In this article we will learn how to dynamically create components in Angular.

First, we need a component.

For the simplicity we are going to use a simple alert component that will take as Input the alert type.

Next, If you think about it, eventually components are actually DOM elements so if you need to insert an element, you need a place to “put” it.

In Angular this place is called a container.

In the my-app component, we are creating a template element. We are also using the hash symbol (#) to declare a reference variable named alertContainer. The template element is the place, or in the Angular world, the container.

Note: The container can be any DOM element or component.

Now we need to get a reference to our template element in my-app component.

We can get a reference to the template element with the ViewChild decorator that also takes a local variable as parameter.

The default return from the ViewChild decorator is the component instance or the DOM element, but in our case, we need to get the element as ViewContainerRef .

As the name suggests ViewContainerRef is a reference to a container. ViewContainerRef stores a reference to the template element ( our container ) and also exposes an API to create components.

You can see the nativeElementLet’s add two buttons that will help us to create…

Dynamically Creating Components With Angular – Netanel Basal