3

只是想将 angular-fontawesome 与 Storybook.js 一起用作库(FaIconLibrary)。在以下文档中https://github.com/FortAwesome/angular-fontawesome/blob/master/docs/usage/icon-library.md#using-the-icon-library我要向构造函数添加一个属性。仅在 Storybook.js 文件 (index.stories.ts) 中,我看不到任何向构造函数添加任何内容的方法,因为它不存在。有人解决这个问题或有一个好的解决方法吗?谢谢

4

1 回答 1

6

一种选择是在加载故事书时使用 Angular 的APP_INITIALIZER函数来执行任意代码。在这种特殊情况下,您可以FaIconLibrary在应用程序初始化过程中使用必要的图标进行配置。

假设您有以下使用的组件,fa-icon并且您想在故事书中使用它:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-user-detail',
  template: `
    <h1>
      <fa-icon icon="user"></fa-icon>
      {{ fullName }}
    </h1>
    <p>Full name: {{ fullName }}</p>
  `,
})
export class UserDetailComponent {
  @Input()
  fullName: string;
}

在此组件的故事书中,您可以APP_INITIALIZERmoduleMetadata调用中提供一个。加载故事书时将执行此代码并将配置FaIconLibrary

import { APP_INITIALIZER } from '@angular/core';
import { FaIconLibrary, FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { faUser } from '@fortawesome/free-solid-svg-icons';
import { moduleMetadata, storiesOf } from '@storybook/angular';
import { UserDetailComponent } from '../app/user-detail.component';

storiesOf('User Detail', module)
  .addDecorator(
    moduleMetadata({
      imports: [ FontAwesomeModule ],
      declarations: [ UserDetailComponent ],
      // The key bit is the providers array below.
      providers: [
        {
          provide: APP_INITIALIZER,
          useFactory: (iconLibrary: FaIconLibrary) => {
            return async () => {
              // Add the necessary icons inside the initialiser body.
              iconLibrary.addIcons(faUser);
            };
          },
          // When using a factory provider you need to explicitly specify its 
          // dependencies.
          deps: [ FaIconLibrary ],
          multi: true,
        },
      ],
    }),
  )
  .add('default', () => {
    return {
      template: `<app-user-detail [fullName]="fullName"></app-user-detail>`,
      props: {
        fullName: 'John Doe',
      },
    };
  });

完整的代码也可以在GitHub上找到。

于 2019-11-02T15:00:04.547 回答