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!

Looking for some help? 🤝
Connect with me on TwitterLinkedIn Github

--

--

Jonathan Gelin

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