AFSpawnService
This is an Angular/TypeScript service that will dynamically create components in Angular, and attach them to a view.
The current version of this repo supports installing AFSpawnService
into your project
via npm, and using the service to init your own components on-the-fly.
AFSpawnService
To learn more about If you want to know more about AFSpawnService
, or you need to understand the need
for the service, please check out my talk about CAAS: Components As A Service.
How to use AFSpawnService?
Install
npm install --save afspawnservice
Import
import { AFSpawnService } from 'afspawnservice'
Inject
In a component/module/service file, you will want to inject the AFSpawnService
appModule.entryComponents
Add to In order to be able to spawn a component like this, you have to tell Angular that this component is an
entryComponent
. This means that it isn't a child component of any other components. It is a top-level
component. If you don't do this, you can't dynamically create the component with AFSpawnService
.
Here is how you do this:
Spawning a component
First import the component class that you want to spawn, and then call the spawn service, and pass in the class to it.
Note: that since there was no second parameter provided, the spawned component will be attached to the document.body
//inside the class
Providing a ViewContainerRef
If you provide a second argument, and that second argument is a ViewContainerRef
, then AFSpawnService
will attach
the spawned component to the provided ViewContainerRef
.
In order to get access to a ViewContainerRef
, you can add a Template Reference Variable
to your template on the element that you would like to append the spawned component to. Then in your class, you can get
access to that part of the template by annotating your class like so:
This will attach the spawned component to to view that you provided.
Passing Inputs and Outputs
There are two ways to pass inputs/outputs to the spawned component. The first is by passing a key/value object as the third
parameter to the createComponent
method.
The second way is by saving the result of the createComponent
call, and then call .next()
on it with a key/value object.
The keys needs to match the names of the inputs and outputs.
//First way ||| HERE ||| this.spawnService.createComponentFooComponent, this.temprefvar, //Second Way;spawnRef.next;
You can call .next()
on the spawnReference
as often as you would like. It will continue to update the values on your spawned component.
Let me know if you have questions.
If there are any questions, please file an issue.
Contributing
This Repo is accepting Pull Requests.
This project was generated with Angular CLI version 1.0.2.