Reputation: 3844
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:
<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?
Upvotes: 14
Views: 1390
Reputation: 115
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.
Upvotes: 1
Reputation: 5562
This is not possible with Angular until Custom Elements is added (which was announced Q4 2017 but the github repo has been archived for some reason, so I'm not sure if CE will continue to be developed).
What you could do is use Stencil to build your components. They are very similar (use typescript) to how you build components in Angular - such components can then be loaded by Angular itself (with some basic config) or any other framework or even in just a plain vanilla HTML/JS setup.
For example, here is a basic Stencil component.
The major difference to angular is that there is no separate template HTML file, but instead it uses JSX to render the template.
The 3rd party would be able to insert these components at a specific place.
Your developers could add the components to an Angular project for whatever purpose you need them to be in Angular.
Upvotes: 0
Reputation: 71
Maybe ask why they want Angular 2 components specifically?
We've coded a standalone "widget" consisting of a javascript API, UI and styling. The developer of an app calls a javascript function to trigger it.
Everything the dev needs is packaged with zero library dependencies.
Your alternative is to rather develop the components minus the UI (e.g. closures/SEF). The client app can then use whatever tech they want for the UI.
Upvotes: 0