Skip to content

Commit

Permalink
feat(component): add support for component generic
Browse files Browse the repository at this point in the history
With backwards compatibility to `any` type. Also remove deprecated factory resolver for component
creation.
  • Loading branch information
gund committed Dec 16, 2021
1 parent ffe81ba commit fe8bb5d
Showing 1 changed file with 12 additions and 16 deletions.
28 changes: 12 additions & 16 deletions projects/ng-dynamic-component/src/lib/dynamic.component.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
Component,
ComponentFactoryResolver,
ComponentRef,
EventEmitter,
Injector,
Expand All @@ -12,7 +11,6 @@ import {
Type,
ViewContainerRef,
} from '@angular/core';

import {
DynamicComponentInjector,
DynamicComponentInjectorToken,
Expand All @@ -25,9 +23,11 @@ import {
{ provide: DynamicComponentInjectorToken, useExisting: DynamicComponent },
],
})
export class DynamicComponent implements OnChanges, DynamicComponentInjector {
export class DynamicComponent<C = any>
implements OnChanges, DynamicComponentInjector
{
@Input()
ndcDynamicComponent: Type<any>;
ndcDynamicComponent: Type<C>;
@Input()
ndcDynamicInjector: Injector;
@Input()
Expand All @@ -36,14 +36,11 @@ export class DynamicComponent implements OnChanges, DynamicComponentInjector {
ndcDynamicContent: any[][];

@Output()
ndcDynamicCreated: EventEmitter<ComponentRef<any>> = new EventEmitter();
ndcDynamicCreated: EventEmitter<ComponentRef<C>> = new EventEmitter();

componentRef: ComponentRef<any> | null;
componentRef: ComponentRef<C> | null;

constructor(
private vcr: ViewContainerRef,
private cfr: ComponentFactoryResolver,
) {}
constructor(private vcr: ViewContainerRef) {}

ngOnChanges(changes: SimpleChanges) {
if (changes.ndcDynamicComponent) {
Expand All @@ -56,12 +53,11 @@ export class DynamicComponent implements OnChanges, DynamicComponentInjector {
this.componentRef = null;

if (this.ndcDynamicComponent) {
this.componentRef = this.vcr.createComponent(
this.cfr.resolveComponentFactory(this.ndcDynamicComponent),
0,
this._resolveInjector(),
this.ndcDynamicContent,
);
this.componentRef = this.vcr.createComponent(this.ndcDynamicComponent, {
index: 0,
injector: this._resolveInjector(),
projectableNodes: this.ndcDynamicContent,
});
this.ndcDynamicCreated.emit(this.componentRef);
}
}
Expand Down

0 comments on commit fe8bb5d

Please sign in to comment.