DEV Community

Saulo Dias
Saulo Dias

Posted on

7 1

Working with ng-content on Storybook

Very often when creating a new story for an Angular component on Storybook you might need to insert content into components which have an ng-content area inside them.

To do that you need to create a template for your story.

Here is a simple component, which has a div with and an ng-content area inside it. The component has two inputs, width and height.

// paper.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'cx-paper',
  template: `
    <div class="paper" [ngStyle]="{ width: width, height: height }">
      <ng-content></ng-content>
    </div>
  `,
  styles: [
    `
      .paper {
        border: navy solid 2px;
        padding: 10px;
      }
    `,
  ],
})
export class PaperComponent {
  @Input()
  width: string;

  @Input()
  height: string;
}
Enter fullscreen mode Exit fullscreen mode

The story for this component

// paper.stories.ts
import { Story, Meta } from '@storybook/angular';
import { PaperComponent } from './paper.component';

export default {
  title: 'Example/Paper',
  component: PaperComponent,
} as Meta;

const Template: Story<PaperComponent> = (args: PaperComponent) => ({
  props: args,
  template: `
  <cx-paper [height]="height" [width]="width">
  This is a template test.
  </cx-paper>`,
});

export const SimpleExample = Template.bind({});

SimpleExample.args = {
  height: '50px',
  width: '300px',
} as Partial<PaperComponent>;
Enter fullscreen mode Exit fullscreen mode

Which should render like this:
image

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (4)

Collapse
 
caraie profile image
Carlos Aiello • Edited

Why the show code part is not showing the content?
This text is missing in the code: "This is a template test."

Collapse
 
sarcevicantonio profile image
Antonio Sarcevic

Now this works for writing stories but it doesn't work right with the ArgsTable and doesn't show any output actions for me at least :z

Collapse
 
saulodias profile image
Saulo Dias • Edited

If by ArgsTable you mean the component inputs, it's working fine for me. I change the inputs and can see the component respond to those changes. I haven't been able to figure out how to make Actions work with a template like that yet.

Collapse
 
sarcevicantonio profile image
Antonio Sarcevic

ArgTable works in the story view but doesn’t in the docs view / docs page.
If this actually works someday that would be very nice but right now storybook for angular is such a pain :z

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs