Documenting Angular components: Storybook

Share This Post

Table of Contents

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. 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.

  Learning Angular as a React Developer

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.

  Migrate from JavaScript to TypeScript

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.

  Analyzing functionalities in Rust
CTA Software

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.

Author

  • David Brito

    Frontend developer since 2011. It all started in 2008 when, as a music enthusiast, he wanted to create an online magazine about independent music and was not satisfied with just a WordPress. That's how he signed up for a course in HTML, CSS and JavaScript. From them I’ve been working for differet companies as front end developer feeling comfortable working with any framework (React, Angular, Node, React Native) going deeper in the software engineering and JavaScrit logic.

2 Comments

  1. Charles Robertson

    This is a great article, and although I see the point of cataloging components for ease of reuse, I cannot help but think that Storyboard will create yet another diversion, from our core programming duties. As a developer, I already spend a great deal of time, adding notes to confluence, code reviewing, unit testing and writing JIRA tickets. And now we have to spend extra time creating documentation and crafting components within Storyboard.
    I mean what is wrong with just creating reusable components and adding them to the src/app/shared/components folder?

  2. David Brito

    Thanks for your comment, Charles. You are right in what you say and we could open a very interesting debate about the diversity of tasks and roles that we developers have to take on more and more. But it is also true that documenting is essential, and this tool allows it with little code and without the need to maintain an external documentation project.
    Furthermore, it is very common to add functionalities that already existed in components, just because we didn’t have a global perspective of them. This added value, especially in large teams, can potentially save wasted development time.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Subscribe To Our Newsletter

Get updates from our latest tech findings

Have a challenging project?

We Can Work On It Together

apiumhub software development projects barcelona
Secured By miniOrange