DEV Community

Gaëtan Redin
Gaëtan Redin

Posted on • Originally published at Medium on

Story for a Component With Content Projection

Storybook and Angular components

Context : Angular 12, StoryBook 6.3.9

Hey, I started to use Storybook and I would Like to share my experience. Here’s the use case. I have a simple component which only use content projection:

@Component({
  selector: "adr-label",
  template: `<ng-content></ng-content>`,
})
_export class_ LabelComponent {}
Enter fullscreen mode Exit fullscreen mode

Here’s the associated story:

_export default_ {
  title: "atoms/forms/label",
  component: LabelComponent,
  decorators: [**componentWrapperDecorator** (LabelComponent)],
} _as Meta_;

_const_ BasicTemplate: _Story_<LabelComponent> = (args) => ({
  moduleMetadata: { declarations: [InputDirective] },
  **template** : `<adr-label>{{ ngContent }}</adr-label>`,
  props: { ...args },
});

_export const_ Default = BasicTemplate.bind({});
Default.args = {
  **ngContent** : "Un label",
};
Enter fullscreen mode Exit fullscreen mode

The specificity here is to use a componentWrapperDecorator. It allows to wrap our component and to pass it some extras like in my case a text content.

You just have to define a template like in BasicTemplate to emulate the content projection and using it like an input.

In the Default args, I add an ngContent arg to set the content of my label. I choose this name “ngContent” because it appears in the controls list and I find it consistent to let know that’s a content projection in this way.

You can see the result here:

Storybook

You can access to the full code here:

atomic-design/src/components/atoms/forms/label at master · GaetanRdn/atomic-design

Learn More

Top comments (0)