forked from storybookjs/storybook
/
ComponentClassFromStoryTemplate.ts
50 lines (44 loc) 路 1.51 KB
/
ComponentClassFromStoryTemplate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { Inject, ChangeDetectorRef, Component, OnDestroy, OnInit, Type } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { ICollection } from '../types';
import { STORY_PROPS } from './app.token';
import { RenderNgAppService } from './RenderNgAppService';
/**
* Wraps the story template into a component
*
* @param template {string}
* @param styles {string[]}
*/
export const createComponentClassFromStoryTemplate = (
template: string,
styles: string[]
): Type<any> => {
@Component({
selector: RenderNgAppService.SELECTOR_STORYBOOK_WRAPPER,
template,
styles,
})
class StoryBookTemplateWrapperComponent implements OnInit, OnDestroy {
private storyPropsSubscription: Subscription;
// eslint-disable-next-line no-useless-constructor
constructor(
@Inject(STORY_PROPS) private storyProps$: Subject<ICollection | undefined>,
private changeDetectorRef: ChangeDetectorRef
) {}
ngOnInit(): void {
// Subscribes to the observable storyProps$ to keep these properties up to date
this.storyPropsSubscription = this.storyProps$.subscribe((storyProps = {}) => {
// All props are added as component properties
Object.assign(this, storyProps);
this.changeDetectorRef.detectChanges();
this.changeDetectorRef.markForCheck();
});
}
ngOnDestroy(): void {
if (this.storyPropsSubscription != null) {
this.storyPropsSubscription.unsubscribe();
}
}
}
return StoryBookTemplateWrapperComponent;
};