Working with ng-content on Storybook

Saulo Dias - Sep 7 '21 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .