项目作者: gund

项目描述 :
Dynamic components with full life-cycle support for inputs and outputs for Angular
高级语言: TypeScript
项目地址: git://github.com/gund/ng-dynamic-component.git
创建时间: 2017-02-16T18:27:31Z
项目社区:https://github.com/gund/ng-dynamic-component

开源协议:MIT License

下载


ng-dynamic-component

Dynamic components with full life-cycle support for inputs and outputs

Release Workflow
Test Workflow
Appveyor
Coverage
Maintainability
Npm
Npm Downloads
Licence
semantic-release

Hey! There is a proposal for new API!

So if you are using this library please give your vote/feedback.


Compatibility with Angular

| Angular | ng-dynamic-component | NPM package |
| ———— | —————————— | ——————————————— |
| >=14.1.3 | 10.3.1 | ng-dynamic-component@^10.3.1 |
| >=14.x.x | 10.2.x | ng-dynamic-component@^10.2.0 |
| 13.x.x | 10.1.x | ng-dynamic-component@~10.1.0 |
| 12.x.x | 9.x.x | ng-dynamic-component@^9.0.0 |
| 11.x.x | 8.x.x | ng-dynamic-component@^8.0.0 |
| 10.x.x | 7.x.x | ng-dynamic-component@^7.0.0 |
| 9.x.x | 6.x.x | ng-dynamic-component@^6.0.0 |
| 8.x.x | 5.x.x | ng-dynamic-component@^5.0.0 |
| 7.x.x | 4.x.x | ng-dynamic-component@^4.0.0 |
| 6.x.x | 3.x.x | ng-dynamic-component@^3.0.0 |
| 5.x.x | 2.x.x | ng-dynamic-component@^2.0.0 |
| 4.x.x | 1.x.x | ng-dynamic-component@^1.0.0 |
| 2.x.x | 0.x.x | ng-dynamic-component@^0.0.0 |

Installation

  1. $ npm install ng-dynamic-component --save

Usage

DynamicComponent

Import DynamicModule where you need to render dynamic components:

  1. import { DynamicModule } from 'ng-dynamic-component';
  2. @NgModule({
  3. imports: [DynamicModule],
  4. })
  5. export class MyModule {}

Then in your component’s template include <ndc-dynamic> where you want to render component
and bind from your component class type of component to render:

  1. @Component({
  2. selector: 'my-component',
  3. template: ` <ndc-dynamic [ndcDynamicComponent]="component"></ndc-dynamic> `,
  4. })
  5. class MyComponent {
  6. component = Math.random() > 0.5 ? MyDynamicComponent1 : MyDynamicComponent2;
  7. }

Standalone API

Since v10.7.0

You may use <ndc-dynamic> as a standalone component:

  1. import { DynamicComponent } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: ` <ndc-dynamic [ndcDynamicComponent]="component"></ndc-dynamic> `,
  5. imports: [DynamicComponent],
  6. standalone: true,
  7. })
  8. class MyComponent {
  9. component = Math.random() > 0.5 ? MyDynamicComponent1 : MyDynamicComponent2;
  10. }

NOTE: Hovewer you should be aware that this will only import <ndc-dynamic>
into your component and nothing else so things like dynamic inputs/outputs
will not work and you will have to import them separately (see their respective sections).

If you still need to use both <ndc-dynamic> and dynamic inputs/outputs it is recommended
to keep using DynamicModule API.

Singal based inputs/outputs

Since v10.8.0

If you want to dynamically render signal based components - see signal-component-io package.

NgComponentOutlet

You can also use NgComponentOutlet
directive from @angular/common instead of <ndc-dynamic>.

Import DynamicIoModule where you need to render dynamic inputs:

  1. import { DynamicIoModule } from 'ng-dynamic-component';
  2. @NgModule({
  3. imports: [DynamicIoModule],
  4. })
  5. export class MyModule {}

Now apply ndcDynamicInputs and ndcDynamicOutputs to ngComponentOutlet:

  1. @Component({
  2. selector: 'my-component',
  3. template: `<ng-template [ngComponentOutlet]="component"
  4. [ndcDynamicInputs]="inputs"
  5. [ndcDynamicOutputs]="outputs"
  6. ></ng-template>`
  7. })
  8. class MyComponent {
  9. component = MyDynamicComponent1;
  10. inputs = {...};
  11. outputs = {...};
  12. }

Also you can use ngComponentOutlet with * syntax:

  1. @Component({
  2. selector: 'my-component',
  3. template: `<ng-container *ngComponentOutlet="component;
  4. ndcDynamicInputs: inputs;
  5. ndcDynamicOutputs: outputs"
  6. ></ng-container>`
  7. })
  8. class MyComponent {
  9. component = MyDynamicComponent1;
  10. inputs = {...};
  11. outputs = {...};
  12. }

Standalone API

Since v10.7.0

You may use dynamic inputs/outputs with *ngComponentOutlet as a standalone API:

  1. import { ComponentOutletInjectorModule } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `<ng-container *ngComponentOutlet="component;
  5. ndcDynamicInputs: inputs;
  6. ndcDynamicOutputs: outputs"
  7. ></ng-container>`
  8. imports: [ComponentOutletInjectorModule],
  9. standalone: true,
  10. })
  11. class MyComponent {
  12. component = MyDynamicComponent1;
  13. inputs = {...};
  14. outputs = {...};
  15. }

If you want to use standard dynamic inputs/outputs with ngComponentOutlet as a standalone API
you need to add the DynamicIoDirective to your imports:

  1. import { DynamicIoDirective, ComponentOutletInjectorModule } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `<ng-container *ngComponentOutlet="component;
  5. ndcDynamicInputs: inputs;
  6. ndcDynamicOutputs: outputs"
  7. ></ng-container>`
  8. imports: [DynamicIoDirective, ComponentOutletInjectorModule],
  9. standalone: true,
  10. })
  11. class MyComponent {
  12. component = MyDynamicComponent1;
  13. inputs = {...};
  14. outputs = {...};
  15. }

Inputs and Outputs

You can pass inputs and outputs to your dynamic components:

Import module DynamicIoModule and then in template:

  1. @Component({
  2. selector: 'my-component',
  3. template: `
  4. <ndc-dynamic
  5. [ndcDynamicComponent]="component"
  6. [ndcDynamicInputs]="inputs"
  7. [ndcDynamicOutputs]="outputs"
  8. ></ndc-dynamic>
  9. `,
  10. })
  11. class MyComponent {
  12. component = MyDynamicComponent1;
  13. inputs = {
  14. hello: 'world',
  15. something: () => 'can be really complex',
  16. };
  17. outputs = {
  18. onSomething: (type) => alert(type),
  19. };
  20. }
  21. @Component({
  22. selector: 'my-dynamic-component1',
  23. template: 'Dynamic Component 1',
  24. })
  25. class MyDynamicComponent1 {
  26. @Input()
  27. hello: string;
  28. @Input()
  29. something: Function;
  30. @Output()
  31. onSomething = new EventEmitter<string>();
  32. }

Here you can update your inputs (ex. inputs.hello = 'WORLD') and they will trigger standard Angular’s life-cycle hooks
(of course you should consider which change detection strategy you are using).

Standalone API

Since v10.7.0

You can use standalone API to pass dynamic inputs/outputs
using DynamicIoDirective with DynamicComponent or ngComponentOutlet:

  1. import { DynamicIoDirective, DynamicComponent } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `
  5. <ndc-dynamic
  6. [ndcDynamicComponent]="component"
  7. [ndcDynamicInputs]="inputs"
  8. [ndcDynamicOutputs]="outputs"
  9. ></ndc-dynamic>
  10. `,
  11. imports: [DynamicIoDirective, DynamicComponent]
  12. })
  13. class MyComponent {
  14. component = MyDynamicComponent1;
  15. inputs = {...};
  16. outputs = {...};
  17. }

Output template variables

Since v6.1.0

When you want to provide some values to your output handlers from template -
you can do so by supplying a special object to your output that has shape {handler: fn, args: []}:

  1. @Component({
  2. selector: 'my-component',
  3. template: `
  4. <ndc-dynamic
  5. [ndcDynamicComponent]="component"
  6. [ndcDynamicOutputs]="{
  7. onSomething: { handler: doSomething, args: ['$event', tplVar] }
  8. }"
  9. ></ndc-dynamic>
  10. `,
  11. })
  12. class MyComponent {
  13. component = MyDynamicComponent1;
  14. tplVar = 'some value';
  15. doSomething(event, tplValue) {}
  16. }

Here you can specify at which argument event value should arrive via '$event' literal.

HINT: You can override event literal by providing
IoEventArgumentToken in DI.

Output Handler Context

Since v10.4.0

You can specify the context (this) that will be used when calling
the output handlers by providing either:

  • IoEventContextToken - which will be;
    injected and used directly as a context value
  • IoEventContextProviderToken - which
    will be provided and instantiated within the IoService and used as a context value.
    This useful if you have some generic way of retrieving a
    context for every dynamic component so you may encapsulate
    it in an Angular DI provider that will be instantiated
    within every component’s injector;

Example using your component as an output context:

  1. import { IoEventContextToken } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `
  5. <ndc-dynamic
  6. [ndcDynamicComponent]="component"
  7. [ndcDynamicOutputs]="{
  8. onSomething: doSomething
  9. }"
  10. ></ndc-dynamic>
  11. `,
  12. providers: [
  13. {
  14. provide: IoEventContextToken,
  15. useExisting: MyComponent,
  16. },
  17. ],
  18. })
  19. class MyComponent {
  20. component = MyDynamicComponent1;
  21. doSomething(event) {
  22. // Here `this` will be an instance of `MyComponent`
  23. }
  24. }

Component Creation Events

You can subscribe to component creation events, being passed a reference to the ComponentRef:

  1. @Component({
  2. selector: 'my-component',
  3. template: `
  4. <ndc-dynamic
  5. [ndcDynamicComponent]="component"
  6. (ndcDynamicCreated)="componentCreated($event)"
  7. ></ndc-dynamic>
  8. `,
  9. })
  10. class MyComponent {
  11. component = MyDynamicComponent1;
  12. componentCreated(compRef: ComponentRef<any>) {
  13. // utilize compRef in some way ...
  14. }
  15. }

Attributes

Since v2.2.0 you can now declaratively set attributes, as you would inputs, via ndcDynamicAttributes.

Import module DynamicAttributesModule and then in template:

  1. import { AttributesMap } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `
  5. <ndc-dynamic
  6. [ndcDynamicComponent]="component"
  7. [ndcDynamicAttributes]="attrs"
  8. ></ndc-dynamic>
  9. `,
  10. })
  11. class MyComponent {
  12. component = MyDynamicComponent1;
  13. attrs: AttributesMap = {
  14. 'my-attribute': 'attribute-value',
  15. class: 'some classes',
  16. };
  17. }

Remember that attributes values are always strings (while inputs can be any value).
So to have better type safety you can use AttributesMap interface for your attributes maps.

Also you can use ngComponentOutlet and ndcDynamicAttributes with * syntax:

  1. import { AttributesMap } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `
  5. <ng-container
  6. *ngComponentOutlet="component; ndcDynamicAttributes: attrs"
  7. ></ng-container>
  8. `,
  9. })
  10. class MyComponent {
  11. component = MyDynamicComponent1;
  12. attrs: AttributesMap = {
  13. 'my-attribute': 'attribute-value',
  14. class: 'some classes',
  15. };
  16. }

Standalone API

Since v10.7.0

You can use standalone API to pass dynamic inputs/outputs
using DynamicAttributesDirective with DynamicComponent or ngComponentOutlet:

  1. import { DynamicAttributesDirective, DynamicComponent } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `
  5. <ndc-dynamic
  6. [ndcDynamicComponent]="component"
  7. [ndcDynamicAttributes]="attrs"
  8. ></ndc-dynamic>
  9. `,
  10. imports: [DynamicAttributesDirective, DynamicComponent]
  11. })
  12. class MyComponent {
  13. component = MyDynamicComponent1;
  14. attrs: AttributesMap = {...};
  15. }

Directives (experimental)

Since v3.1.0 you can now declaratively set directives, via ndcDynamicDirectives.

NOTE:
There is a known issue with OnChanges hook not beign triggered on dynamic directives
since this part of functionality has been removed from the core as Angular now
supports this out of the box for dynamic components.

In dynamic directives queries like @ContentChild and host decorators like @HostBinding
will not work due to involved complexity required to implement it (but PRs are welcome!).

Import module DynamicDirectivesModule and then in template:

  1. import { dynamicDirectiveDef } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `
  5. <ng-container
  6. [ngComponentOutlet]="component"
  7. [ndcDynamicDirectives]="dirs"
  8. ></ng-container>
  9. `,
  10. })
  11. class MyComponent {
  12. component = MyDynamicComponent1;
  13. dirs = [dynamicDirectiveDef(MyDirective)];
  14. }

It’s also possible to bind inputs and outputs to every dynamic directive:

  1. import { dynamicDirectiveDef } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `
  5. <ng-container
  6. [ngComponentOutlet]="component"
  7. [ndcDynamicDirectives]="dirs"
  8. ></ng-container>
  9. `,
  10. })
  11. class MyComponent {
  12. component = MyDynamicComponent1;
  13. directiveInputs = { prop1: 'value' };
  14. directiveOutputs = { output1: (evt) => this.doSomeStuff(evt) };
  15. dirs = [
  16. dynamicDirectiveDef(
  17. MyDirective,
  18. this.directiveInputs,
  19. this.directiveOutputs,
  20. ),
  21. ];
  22. }

To change inputs, just update the object:

  1. class MyComponent {
  2. updateDirectiveInput() {
  3. this.directiveInputs.prop1 = 'new value';
  4. }
  5. }

You can have multiple directives applied to same dynamic component (only one directive by same type):

  1. import { dynamicDirectiveDef } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `
  5. <ng-container
  6. [ngComponentOutlet]="component"
  7. [ndcDynamicDirectives]="dirs"
  8. ></ng-container>
  9. `,
  10. })
  11. class MyComponent {
  12. component = MyDynamicComponent1;
  13. dirs = [
  14. dynamicDirectiveDef(MyDirective1),
  15. dynamicDirectiveDef(MyDirective2),
  16. dynamicDirectiveDef(MyDirective3),
  17. dynamicDirectiveDef(MyDirective1), // This will be ignored because MyDirective1 already applied above
  18. ];
  19. }

Standalone API

Since v10.7.0

You can use standalone API to pass dynamic inputs/outputs
using DynamicDirectivesDirective with DynamicComponent or ngComponentOutlet:

  1. import { DynamicDirectivesDirective, DynamicComponent } from 'ng-dynamic-component';
  2. @Component({
  3. selector: 'my-component',
  4. template: `
  5. <ng-container
  6. [ngComponentOutlet]="component"
  7. [ndcDynamicDirectives]="dirs"
  8. ></ng-container>
  9. `,
  10. imports: [DynamicDirectivesDirective, DynamicComponent]
  11. })
  12. class MyComponent {
  13. component = MyDynamicComponent1;
  14. dirs = [...];
  15. }

Extra

You can have more advanced stuff over your dynamically rendered components like setting custom injector ([ndcDynamicInjector])
or providing additional/overriding providers ([ndcDynamicProviders]) or both simultaneously
or projecting nodes ([ndcDynamicContent]).

Since v10.6.0: You can provide custom NgModuleRef ([ndcDynamicNgModuleRef])
or EnvironmentInjector ([ndcDynamicEnvironmentInjector]) for your dynamic component.


NOTE: In practice functionality of this library is split in two pieces:

  • one - component (ndc-dynamic) that is responsible for instantiating and rendering of dynamic components;
  • two - directive (ndcDynamic also bound to ndc-dynamic) that is responsible for carrying inputs/outputs
    to/from dynamic component by the help of so called
    DynamicComponentInjector.

Thanks to this separation you are able to connect inputs/outputs and life-cycle hooks to different mechanisms of injecting
dynamic components by implementing DynamicComponentInjector and providing it via
DynamicComponentInjectorToken in DI.

It was done to be able to reuse NgComponentOutlet added in Angular 4-beta.3.

To see example of how to implement custom component injector - see
ComponentOutletInjectorDirective
that is used to integrate NgComponentOutlet directive with inputs/outputs.

Contributing

You are welcome to contribute to this project.
Simply follow the contribution guide.

License

MIT © malkevich.alex@gmail.com">Alex Malkevich