一种选择是在加载故事书时使用 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;
}
在此组件的故事书中,您可以在moduleMetadata 调用中提供APP_INITIALIZER。此代码将在加载故事书时执行并配置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上找到。