Documenting Angular components: Storybook
Tags: agilewebandappdevelo
Published: 2022-01-24 17:17:13

---
title: Documenting Angular components: Storybook
published: true
date: 2021-12-28 09:30:00 UTC
tags: Agilewebandappdevelo
canonical_url: https://apiumhub.com/tech-blog-barcelona/documenting-angular-components-storybook/
---

As developers, in our daily work we like to find good documentation of the libraries and technologies we use. It is, therefore, our responsibility to leave our work well documented. Those who come after us to use it and/or continue it will appreciate it. At Apiumhub we are very fond of documenting our projects.

There are many tools that allow us to write documentation in Markdown (.md) format, and some others that also allow us to document our UI components. Most of them are written and focused for React. What happens then if we want to document the components of our Angular project?

One of the most popular tools to document our UI components is [**Storybook**](https://storybook.js.org/). It is an ideal tool to create our UI library in an independent and reusable way. It is also one of the few that allow us to interact with the components. And although its creators claim that it is focused on multiple frameworks that follow a Component Driven Architecture, in which Angular is included, the truth is that being based on JSX, using Stories of Angular components in .mdx files (the format that combines Markdown and JSX) is not as easy as they claim, some features do not work, the Storybook documentation itself for Angular even has some examples written in React and, if we make a quick check on the net, we will realize that many Angular developers encounter common problems: confusion and lack of solutions.

## Using Storybook

Let’s try to show some examples that can help us understand how it works:

We install Storybook from our Angular project root with the following command:

```
npx sb init
```

If everything went well, the _npm run storybook_ command should run our Storybook. We will also see that a .storybook folder has been created in the root of the project with several configuration files inside. The version of Storybook used at the time of writing this article is _v6.4.9_. This version already automatically installs and configures _Compodocs_, a tool that analyzes our project and generates automatic documentation that we can then adapt and use. This did not happen in previous versions and we had to do it manually.

A **Story** is the capture of a component’s state. This means that we will create as many stories as component states we want to show. Storybook already provided us with some examples once we installed it. We will work on the example of the primary button:

```
import { Story, Meta } from '@storybook/angular/types-6-0';
import Button from './button.component';

export default {
 title: 'Components/UI/CSF Stories',
 component: Button,
 argTypes: {
   backgroundColor: { control: 'color' },
 },
} as Meta;

const Template: Story<Button> = (args: Button) => ({
 props: args,
});

export const Primary = Template.bind({});
Primary.args = {
 primary: true,
 label: 'Button',
};

```

_Primary_ would be our first Story and it will be shown in the left menu under the path indicated in the title parameter. The _Canvas_ tab shows us the component in the indicated state and in the _Docs_ tab, the different properties, editable in real time to change the current state. Something interesting is that it shows us the code to use the component in the current state.

Now let’s face the interesting part: we can write Markdown code in MDX format and embed the stories at the time that suits us. We have 2 ways to do it:

- Create the Stories previously in CSF (Component Story Format) as we have seen before and then create the MDX files that will call each Story when it suits us. If we write the Markdown in this way, we will have in the left menu the CSF on one side and the MDX on the other.

```
import { Meta, Story } from '@storybook/addon-docs';

<Meta title="Components/UI/Embedded stories" />

# Embedded Stories

Lorem ipsum

## Primary button
<Story id='components-ui-csf-stories--primary'></Story>

```

The id is found in the url of each story.

- A much more elegant and powerful way is to write the Stories directly in the MDX. This way we will have a menu item with the title that we indicate and, under it in the form of submenus, all the stories that we have created inside, with the component with its options under the Canvas tab. Under the Docs tab we will have the MDX content, which will be navigable through the menu. Pure elegance. 

```
import { Meta, Story, ArgsTable } from '@storybook/addon-docs';
import Button from './button.component';

<Meta title="Components/UI/MDX Stories" component={Button} />

export const Template = (args) => ({ props: args });

# MDX Stories

Lorem ipsum

## Primary button

<Canvas>
 <Story
   name="Primary"
   args={{
     primary: true,
     label: 'Button',
   }}>
   {Template.bind({})}
 </Story>
 <ArgsTable story='Primary' />
</Canvas>

```

_ArgsTable_ serves to show the argument box that allows us to change the state of the component and to see the code to use the component.

But what if we see now a last case a little more complex? Let’s imagine that we have a component that implements a _ControlValueAccessor_ and we are going to need to create a context where we need a wrapper in the form of a _FormGroup_. That component is the classic _switch button_, with a _label_ parameter and a value controlled by a _formControlName_. The _Story_ could be something like this:

```
import {moduleMetadata} from "@storybook/angular";
import {FormBuilder, FormControl, FormsModule, ReactiveFormsModule} from "@angular/forms";
import {Story} from "@storybook/angular/types-6-0";
import {SwitchComponent} from "./switch.component";

export default {
 title: 'Switch',
 component: SwitchComponent,
 decorators: [
   moduleMetadata({
     declarations: [SwitchComponent],
     imports: [FormsModule, ReactiveFormsModule],
   })
 ]
};

export const SwitchStory: Story = () => {
 let formGroup = new FormBuilder().group({
   agree: new FormControl()
 });
 const label = 'Switch label';

 return {
   template: `<form [formGroup]="group">
               <switch [label]="label" [formControlName]="controlName"></switch>
              </form>`,
   props: {
     group: formGroup,
     controlName: 'agree',
     label
   }
 }
}

```

We need the _ModuleMetadata_ from the @storybook/angular library to define the components and modules needed. Once we have the modules imported, inside the _story_ we prepare the context. In our case, we create the _FormGroup_ using the _FormBuilder_. In the _story_ props section we will define the variables that we have passed to our component and its _wrapper_ in the _template_ property. This is how we have our _ControlValueAccessor_ ready so that it can change its state.

For these examples we have tried to create scenarios as simple as possible, using only the Storybook core and omitting the use of _addons_, but obviously these can be a very powerful tool. _Addons_ are plugins created and maintained by the community that allow us to complement our stories with tools of all kinds, from decorators to test environments. To learn more about _addons_, click [here](https://storybook.js.org/docs/angular/addons/install-addons).

As we have seen, documenting our UI components in this way and with the chance of complementing them with Markdown files, with a little love and dedication we can have a documentation project that is easy to use and very attractive, without the need for complex configurations and having the files together with the components themselves, all in the same project.