angularstorybookangular-storybook

Use properties on storybook component template


Using a class component in a story enables you to pass through properties as arguments:

const Template: Story<MyComponent> = (args) => ({
  props: args,
  component: MyComponent,
})

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

export const Small = Template.bind({});
Small.args = {
  size: 'xs'
}

Magically the arguments are mapped over as props to the component. However, when using a template it does not work:

const Template: Story<FlexDialogModalComponent> = (args) => ({
  props: args,
  template: `
    <app-my-component>test</app-my-component>
  `,
})

Now it seems obvious since it does not know where to add them. So I figured the following should be possible:

const Template: Story<FlexDialogModalComponent> = (args: { dialogModalSize }) => ({
  props: args,
  template: `
    <app-my-component [size]="size">test</app-my-component>
  `,
})

But that does not work. It gives no error but it just does nothing. Someone have an idea how to fix this?


Solution

  • Here are few examples that I think that could help you with your problem.

    // my-component.ts
    import {
      Component,
      Input
    } from '@angular/core';
    
    @Component({
      selector: 'app-my-component',
      templateUrl: './my-component.html'
    })
    export class MyComponent {
      @Input() size: string;
    }
    
    <!--my-component.html-->
    {{size}}
    
    // my-component.stories.ts
    import { CommonModule } from '@angular/common';
    import { moduleMetadata } from '@storybook/angular';
    import { MyComponent } from './my-component';
    
    export default {
      title: 'MyComponent',
      decorators: [
        moduleMetadata({
          imports: [
            CommonModule,
          ], declarations: [
            MyComponent
          ]
        })
      ]
    };
    
    export const Component = () => ({
      component: MyComponent,
      props: {
        size: 'xs'
      }
    })
    
    // "@storybook/addon-controls" is needed (.storybook/main.js) so that you can play with the 'size' property in Storybook in the 'Controls' tab
    export const Template = (args) => ({
      template: `<app-my-component [size]="size"></app-my-component>`,
      props: args
    })
    Template.args = {
      size: 'xs'
    }
    
    // "@storybook/addon-controls" is needed (.storybook/main.js) so that you can play with the 'size' property in Storybook in the 'Controls' tab
    export const ComponentWithControls = (args) => ({
      component: MyComponent,
      props: args
    })
    ComponentWithControls.args = {
      size: 'm'
    }