Created
March 26, 2025 10:24
-
-
Save LayZeeDK/312af70cf3724b84641ddfdfc9c33b83 to your computer and use it in GitHub Desktop.
Get Angular Injector in Storybook 7+ `play` function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injector } from '@angular/core'; | |
import { getStorybookNg } from './get-storybook-ng'; | |
/** | |
* Get root-level injector for a component story. | |
* | |
* @example | |
* play: ({ canvasElement }) = { | |
* const injector = getStorybookInjector(canvasElement); | |
* | |
* runInInjectionContext(injector, () => { | |
* const myService = inject(MyService); | |
* }); | |
* } | |
*/ | |
export function getStorybookInjector(canvasElement: HTMLElement): Injector { | |
const rootElement = canvasElement.querySelector('[ng-version]'); | |
if (rootElement === null) { | |
throw new Error( | |
'Could not resolve Angular root element in the component story' | |
); | |
} | |
const ng = getStorybookNg(canvasElement); | |
return ng.getInjector(rootElement); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ɵGlobalDevModeUtils } from '@angular/core'; | |
import { getStorybookWindow } from './get-storybook-window'; | |
export function getStorybookNg( | |
canvasElement: HTMLElement | |
): ɵGlobalDevModeUtils['ng'] { | |
const storybookWindow = getStorybookWindow(canvasElement); | |
return storybookWindow.ng; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ɵGlobalDevModeUtils } from '@angular/core'; | |
export function getStorybookWindow( | |
canvasElement: HTMLElement | |
): Window & typeof globalThis & ɵGlobalDevModeUtils { | |
const { | |
ownerDocument: { defaultView: storybookWindow }, | |
} = canvasElement; | |
if (storybookWindow === null) { | |
throw new Error('Could not resolve Storybook Window object'); | |
} | |
return storybookWindow as Window & typeof globalThis & ɵGlobalDevModeUtils; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment