Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject Angular 2 components at different DOM nodes on a plain JavaScript page?

Use-case: A client wants to build a library that consist of Angular 2 components but exposes abstracted, technology-agnostic interface to the end user (developer) of that library, so that those users might be using plain JavaScript and not be aware of the internals of the library.

The difficulty comes from the following:

  1. There is a page, which uses plain JavaScript. This page is developed by third-party.
  2. The third-party should be able to insert given Angular 2 component at specific places (DOM nodes) on the page.
  3. Let's say the component is <mg-input> and it should be shown in the header of the plain JavaScript page, but not only there - also in a form down the page. Two different places, two different DOM nodes which have between them plain html.

The question: How do we bootstrap component at specific DOM node and how do we pass configuration (not primitives but a complex object) to those components?

In the React world this is done simply by running ReactDom.render(domEl, <CustomInput nonPrimitiveConfig={config}/>) and depending on what domEl и config is, the component will be rendered in different places with different config.

How to do this in Angular 2?

like image 898
antitoxic Avatar asked Jan 13 '17 08:01

antitoxic


1 Answers

You should be able to use Angular Elements to accomplish this. Angular Elements allows you to create a class that can be registered with most popular browsers as a custom element. The custom element can then be used just like any other DOM element, and includes Angular binding and change detection. Check this out for more details: https://angular.io/guide/elements

Edit: This functionality only exists for Angular 6+. If you are required to use Angular 2, this is not an option.

like image 185
Michael Barrett Avatar answered Oct 08 '22 10:10

Michael Barrett