Inject Angular services in Storybook 7

Learn how to call Angular Injectable directly in Angular Stories by using a custom Storybook decorator

Jonathan Gelin
2 min readJun 18, 2023

Note: This article is an update of my previous article on “Using Angular Services in Storybook 6

Storybook is a powerful tool for creating UI components in isolation across various frameworks.

In Angular, there are instances where accessing the injector context and services directly within stories becomes necessary. For example, when writing a story for opening a Dialog component.

Traditionally, this would require creating a wrapper component to inject the service.

However, I have developed a custom Storybook decorator that simplifies this process by exposing the Angular Injector in story props.

To get started, you’ll need to create the custom decorator in your codebase:

The custom decorator sets up an APP_INITIALIZER provider that executes when the Angular story is bootstrapped. It uses the Angular Factory Provider approach to inject the global Injector service into the story props.

Now, you can configure it directly in your Story:

With the custom decorator in place, the injector property is set in your story props and is directly accessible in the template.

This allows you to provide it to your openDialog function and access all services directly in your story!

I hope this article helps you effectively inject Angular services into your Storybook stories.

If you have any questions or comments, please feel free to leave them below. Happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Jonathan Gelin
Jonathan Gelin

Written by Jonathan Gelin

Write & Share about SDLC/Architecture in Ts/Js, Nx, Angular, DevOps, XP, Micro Frontends, NodeJs, Cypress/Playwright, Storybook, Tailwind • Based in 🇪🇺

Responses (3)

Write a response

Thanks for writing this.
but for me, after it successfully injects the injector into props, the injector is undefined in the template. do you have any idea maybe?

45

I'm having trouble resolving the DecoratorFunction generic type. Can you provide a module I should be importing for that?

1

The injector is successfully injected, but the injector is undefinedin the template, how can this be resolved?