DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Angular Input/Output Signals: The New Component Communication
  • Azure Deployment Using FileZilla
  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators

Trending

  • How to Format Articles for DZone
  • Develop a Reverse Proxy With Caching in Go
  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  • Fixing Common Oracle Database Problems
  1. DZone
  2. Coding
  3. Frameworks
  4. Documenting Angular Components Using Storybook

Documenting Angular Components Using Storybook

One of the most popular tools to document our UI components is Storybook, an ideal tool to create our UI library in an independent and reusable way. Here's how it works.

By 
David Brito user avatar
David Brito
·
Feb. 08, 22 · Analysis
Likes (5)
Comment
Save
Tweet
Share
4.4K Views

Join the DZone community and get the full member experience.

Join For Free

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 for and focused on 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 at 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:

CSS
 
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, which are 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 two 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.
CSS
 
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. 
CSS
 
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 the 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:

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

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.

AngularJS

Published at DZone with permission of David Brito. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Angular Input/Output Signals: The New Component Communication
  • Azure Deployment Using FileZilla
  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!