Working with ng-content on Storybook

saulodias

Saulo Dias

Posted on September 7, 2021

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

💖 💪 🙅 🚩
saulodias
Saulo Dias

Posted on September 7, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Working with ng-content on Storybook
storybook Working with ng-content on Storybook

September 7, 2021