Skip to content

feat(rx-dynamic-component): support data input #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/conways-game-of-life/src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<div style="display: flex">
<div *ngFor="let item of column; trackBy: trackLife" class="cell">
<rx-dynamic-outlet
[factory]="item.component | ngrxPush"
[componentType]="item.component | ngrxPush"
></rx-dynamic-outlet>
</div>
</div>
Expand Down
11 changes: 7 additions & 4 deletions apps/rx-dynamic-component-demo/src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
<button (click)="open()">Open</button>
<rx-dynamic-outlet
[componentType]="queryParamComponent$ | async"
[data]="data$ | async"
></rx-dynamic-outlet>

<div class="query-container">
<div>
Expand All @@ -13,12 +17,11 @@
</select>
</div>
<div style="border: 2px solid orange">
<rx-dynamic-outlet
[factory]="queryParamComponent$ | async"
></rx-dynamic-outlet>
Demo of lazy loaded outlet
<div *ngFor="let el of arr" style="height: 500px; border: black solid">
<rx-lazy-dynamic-outlet [factory]="queryParamComponent$ | async">
<rx-lazy-dynamic-outlet
[componentType]="queryParamComponent$ | async"
>
</rx-lazy-dynamic-outlet>
</div>
</div>
Expand Down
7 changes: 7 additions & 0 deletions apps/rx-dynamic-component-demo/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
import { MatBottomSheet } from '@angular/material/bottom-sheet';
import { ActivatedRoute, Router } from '@angular/router';
import { RxDynamicComponentService } from '@trellisorg/rx-dynamic-component';
import { BehaviorSubject } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';
import { DialogComponent } from './dialog/dialog.component';
import type { QueryParam1Component } from './query-param1/query-param1.component';
Expand All @@ -27,13 +28,19 @@ export class AppComponent {

arr = new Array(100).fill(0);

data$ = new BehaviorSubject<any>({ title: 'this is a title' });

constructor(
private _route: ActivatedRoute,
private rxDynamicComponentService: RxDynamicComponentService,
private _router: Router,
private _matBottomSheet: MatBottomSheet
) {
this.rxDynamicComponentService.loadManifest('service-preload');

setTimeout(() => {
this.data$.next({ title: 'new title', notProp: '' });
}, 3000);
}

changeQueryParams($event: Event): void {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<rx-dynamic-outlet
*ngIf="state$ | async"
[factory]="factory$ | async"
[componentType]="factory$ | async"
></rx-dynamic-outlet>
Original file line number Diff line number Diff line change
@@ -1,30 +1,11 @@
import {
ChangeDetectionStrategy,
Component,
Input,
OnChanges,
SimpleChanges,
} from '@angular/core';
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';

@Component({
selector: 'trellisorg-query-param1',
templateUrl: './query-param1.component.html',
styleUrls: ['./query-param1.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class QueryParam1Component implements OnChanges {
@Input() set title(title: string) {
this._title = title;
console.log(title);
}

get title() {
return this._title;
}

_title: string;

ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
}
export class QueryParam1Component {
@Input() title: string;
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
"lodash.merge": "^4.6.2",
"prettier": "2.3.2",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.0.0",
"rxjs": "^7.4.0",
"socket.io-client": "^4.4.0",
"ts-node": "9.1.1",
"tslib": "^2.0.0",
Expand Down
4 changes: 2 additions & 2 deletions packages/rx-dynamic-component/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,9 @@ export class AppModule {}

```angular2html
<!--Will load the outlet as soon as the observable emits-->
<rx-dynamic-outlet [factory]="queryParamComponent$ | async"></rx-dynamic-outlet>
<rx-dynamic-outlet [componentType]="queryParamComponent$ | async"></rx-dynamic-outlet>
<!--Will load the outlet as soon as the observable emits assuming the component is in view with IntersectionObserver-->
<rx-lazy-dynamic-outlet [factory]="queryParamComponent$ | async"></rx-lazy-dynamic-outlet>
<rx-lazy-dynamic-outlet [componentType]="queryParamComponent$ | async"></rx-lazy-dynamic-outlet>
```

With that when the query params `query` property is equal to one of the manifest entries the corresponding Angular
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
>
<rx-dynamic-outlet
*ngIf="intersected"
[factory]="factory"
[componentType]="factory"
[data]="data"
></rx-dynamic-outlet>
</div>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, ComponentFactory, Input, Type } from '@angular/core';
import { Component, Input, Type } from '@angular/core';

@Component({
// eslint-disable-next-line @angular-eslint/component-selector
Expand All @@ -7,15 +7,18 @@ import { Component, ComponentFactory, Input, Type } from '@angular/core';
styleUrls: ['./lazy-dynamic-outlet.component.scss'],
})
export class LazyDynamicOutletComponent<
TComponentType extends Type<unknown>,
TComponent = InstanceType<TComponentType>
TData extends unknown,
TComponent extends unknown,
TComponentType extends Type<TComponent>
> {
@Input() lazyDynamicOutletConfig: IntersectionObserverInit = {
threshold: [0.25],
rootMargin: '0px',
};

@Input() factory: ComponentFactory<TComponent>;
@Input() componentType: TComponentType;

@Input() data: TData;

intersected = false;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ComponentFactory,
ComponentRef,
Input,
Type,
ViewChild,
ViewContainerRef,
ɵComponentDef,
ɵComponentType,
} from '@angular/core';

@Component({
Expand All @@ -17,26 +19,62 @@ import {
styleUrls: ['./dynamic-outlet.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DynamicOutletComponent<TComponentType extends Type<unknown>, TComponent = InstanceType<TComponentType>>
implements AfterViewInit
export class DynamicOutletComponent<
TData extends unknown,
TComponent extends unknown,
TComponentType extends Type<TComponent>,
TComponentInstance = InstanceType<TComponentType>
> implements AfterViewInit
{
@ViewChild('outlet', { read: ViewContainerRef }) outlet: ViewContainerRef;

private _factory: ComponentFactory<TComponent>;
private _componentType: TComponentType;

@Input() set factory(factory: ComponentFactory<TComponent>) {
@Input() set componentType(componentType: TComponentType) {
if (this.outlet) {
this.loadOutlet(factory);
this.loadOutlet(componentType);
}

this._factory = factory;
this._componentType = componentType;
}

@Input() set data(data: TData) {
this._data = data;

this.setComponentData(this.data);
}

get data(): any {
return this._data;
}

private _data: TData;

private inputs: {
[P in keyof TComponentInstance]: string;
};

private changeDetectorRef: ChangeDetectorRef;

private component: ComponentRef<TComponent>;

ngAfterViewInit(): void {
if (this._factory) {
this.loadOutlet(this._factory);
if (this._componentType) {
this.loadOutlet(this._componentType);
}
}

private setComponentData(data: TData): void {
if (this.component && data) {
Object.entries(data).forEach(([key, value]) => {
if (this.inputs[key]) {
this.component.instance[key] = value;
} else {
console.warn(`Cannot set properties that are not inputs.`);
}
});

this.changeDetectorRef.markForCheck();
}
}

Expand All @@ -47,11 +85,20 @@ export class DynamicOutletComponent<TComponentType extends Type<unknown>, TCompo
* are cleared and removed from the DOM
*
* It will then create the component from the factory using the ViewContainerRef
* @param factory
* @param tComponent
*/
loadOutlet(factory: ComponentFactory<TComponent>): void {
loadOutlet(tComponent: TComponentType): void {
this.outlet.clear();

this.component = this.outlet.createComponent(factory);
this.component = this.outlet.createComponent(tComponent);

this.changeDetectorRef = this.component.injector.get(ChangeDetectorRef);

this.inputs = (
(this.component.componentType as ɵComponentType<TComponentInstance>)
.ɵcmp as ɵComponentDef<TComponentInstance>
).inputs;

this.setComponentData(this.data);
}
}
4 changes: 0 additions & 4 deletions packages/rx-dynamic-component/src/lib/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@ export interface SharedManifestConfig {
/**
* devMode: Will enable logging to debug how things are loaded
* manifests
* cacheFactories: Whether or not to cache the factories that are piped through RxDynamicService (Can be buggy in places)
*
* TODO: allow for caching at the manifest level
*/
export interface DynamicComponentRootConfig<T extends string = string>
extends SharedManifestConfig {
Expand All @@ -45,7 +42,6 @@ export interface DynamicComponentRootConfig<T extends string = string>
export const defaultRootConfig: DynamicComponentRootConfig = {
manifests: [],
devMode: false,
cacheFactories: false,
preload: false,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import {
Optional,
} from '@angular/core';
import type { Observable } from 'rxjs';
import { from, of, throwError } from 'rxjs';
import { catchError, switchMap, tap } from 'rxjs/operators';
import { from, map, of, throwError } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import { Logger } from './logger';
import {
DEFAULT_TIMEOUT,
Expand Down Expand Up @@ -88,33 +88,18 @@ export class RxDynamicComponentService {
TComponent = TComponentType extends Type<infer TComponentInstance>
? TComponentInstance
: TComponentType
>(
componentId: string,
injector?: Injector
): Observable<ComponentFactory<TComponent>> {
>(componentId: string, injector?: Injector): Observable<TComponent> {
const manifest = this.manifests.get(componentId);

if (!manifest) {
if (this.config.devMode) {
this.cannotFindManifest(componentId);
}
return throwError(
`No manifest found for componentId: ${componentId}`
() => `No manifest found for componentId: ${componentId}`
);
}

/*
* Factories can be cached at either the global level or at the manifest level
*/
if (
(manifest.cacheFactories ||
(this.config.cacheFactories &&
manifest.cacheFactories === undefined)) &&
this.componentCache.has(componentId)
) {
return of(this.componentCache.get(componentId));
}

const loadChildren = manifest.loadChildren();

/**
Expand All @@ -138,28 +123,16 @@ export class RxDynamicComponentService {
);
}
}),
switchMap((factory) => {
const moduleRef = factory.create(injector || this._injector);
map((moduleFactory) => {
const moduleRef = moduleFactory.create(
injector ?? this._injector
);

/**
* By providing a DYNAMIC_COMPONENT injection in the module we are loading we know what component it is
* that should be rendered from the declarations array in the module
*/
const dynamicComponentType =
moduleRef.injector.get(DYNAMIC_COMPONENT);

return of(
moduleRef.componentFactoryResolver.resolveComponentFactory<TComponent>(
dynamicComponentType
)
);
}),
tap((componentFactory) => {
if (
this.config.cacheFactories &&
!this.componentCache.has(componentId)
)
this.componentCache.set(componentId, componentFactory);
return moduleRef.injector.get(DYNAMIC_COMPONENT);
}),
catchError((error) => {
if (this.config.devMode) {
Expand All @@ -169,7 +142,7 @@ export class RxDynamicComponentService {
);
}

return throwError(error);
return throwError(() => error);
})
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { switchMap } from 'rxjs/operators';
// eslint-disable-next-line @angular-eslint/component-selector
selector: 'container',
template: ` <rx-dynamic-outlet
[factory]="factory$ | async"
[componentType]="factory$ | async"
></rx-dynamic-outlet>`,
styles: [''],
})
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10234,7 +10234,7 @@ rxjs@^5.5.6:
dependencies:
symbol-observable "1.0.1"

rxjs@^7.0.0, rxjs@^7.2.0, rxjs@^7.4.0:
rxjs@^7.2.0, rxjs@^7.4.0:
version "7.4.0"
resolved "https://registry.npmjs.org/rxjs/-/rxjs-7.4.0.tgz#a12a44d7eebf016f5ff2441b87f28c9a51cebc68"
integrity sha512-7SQDi7xeTMCJpqViXh8gL/lebcwlp3d831F05+9B44A4B0WfsEwUQHR64gsH1kvJ+Ep/J9K2+n1hVl1CsGN23w==
Expand Down