Created
March 26, 2025 10:26
-
-
Save LayZeeDK/2c02877910d75c0f254eaad1f04abbc0 to your computer and use it in GitHub Desktop.
Storybook 7+ decorator to access Angular Injector as `injector` prop
This file contains 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 { | |
APP_INITIALIZER, | |
EnvironmentProviders, | |
FactoryProvider, | |
Injector, | |
makeEnvironmentProviders, | |
} from '@angular/core'; | |
import { AngularRenderer } from '@storybook/angular'; | |
import { DecoratorFunction } from '@storybook/types'; | |
type AngularStorybookDecorator<TArgs = unknown> = DecoratorFunction< | |
AngularRenderer, | |
TArgs | |
>; | |
type StoryFnAngularReturnType = ReturnType<AngularStorybookDecorator>; | |
function provideInjectorProp( | |
story: StoryFnAngularReturnType | |
): EnvironmentProviders { | |
function initializeStory(injector: Injector): () => void { | |
return () => { | |
story.props = { | |
injector, | |
...story.props, | |
}; | |
}; | |
} | |
const storyInitializer: FactoryProvider = { | |
provide: APP_INITIALIZER, | |
multi: true, | |
useFactory: initializeStory, | |
deps: [Injector], | |
}; | |
return makeEnvironmentProviders([storyInitializer]); | |
} | |
/** | |
* Add `injector` to passed props. | |
* | |
* @see https://jgelin.medium.com/inject-angular-services-in-storybook-7-c26b7f5a41e5 by Jonathan Gelin | |
*/ | |
export function withInjectorProp<TArgs = unknown>(): DecoratorFunction< | |
AngularRenderer, | |
TArgs | |
> { | |
return storyFn => { | |
const story = storyFn(); | |
story.applicationConfig ??= { providers: [] }; | |
story.applicationConfig.providers = [ | |
provideInjectorProp(story), | |
...story.applicationConfig.providers, | |
]; | |
return story; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment