I have a Toast component that uses Angular Bootstrap:
@Component({
selector: 'app-toast',
template: `
<ngb-toast
*ngFor="let toast of toastService.toasts"
[header]="toast.headertext"
[class]="toast.classname"
[autohide]="toast.autohide"
[delay]="toast.delay || 5000"
(hide)="toastService.remove(toast)"
>
<ng-template [ngIf]="isTemplate(toast)" [ngIfElse]="text">
<ng-template [ngTemplateOutlet]="toast.textOrTpl"></ng-template>
</ng-template>
<ng-template #text>{{ toast.textOrTpl }}</ng-template>
</ngb-toast>
`,
})
export class ToastComponent {
@HostBinding('class.ngb-toasts') toastClass = true;
constructor(public toastService: ToastService) {}
isTemplate(toast: any) {
return toast.textOrTpl instanceof TemplateRef;
}
}
This component template is called via a Service:
export class ToastService {
toasts: any[] = [];
show(textOrTpl: string | TemplateRef<any>, options: any = {}) {
this.toasts.push({ textOrTpl, ...options });
}
}
So from any component that has <app-toast></app-toast>, I just call the service and the toasts show up, this is all following NG Bootstrap documentation.:
this.toastService.show('Some message', {
classname: 'bg-success text-light',
delay: 2000,
autohide: true,
});
Question: How do I define a story that uses a Service to render the component? As you can see the component does not render the template unless the service is called via the show method. How can I replicate this inside the story?
The story so far:
import { moduleMetadata } from '@storybook/angular';
import { Story, Meta } from '@storybook/angular/types-6-0';
import { ToastComponent } from './toast.component';
import { CommonModule } from '@angular/common';
import { ToastService } from './toast.service';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
export default {
title: 'Toast',
component: ToastComponent,
decorators: [
moduleMetadata({
providers: [ToastService],
imports: [CommonModule, NgbModule],
}),
],
} as Meta;
const Template: Story<ToastComponent> = (args: ToastComponent) => ({
component: ToastComponent,
props: args,
});
export const Primary = Template.bind({});
Tried:
I've tried instantiating a new service in the story but this does not work.
I could also create a demo component just for storybook that calls the show method from the service by itself, but I'd rather not have to create additional components just for storybook for this and any other component and just use as is, as it's easier to manage.
Is there a way to call the service inside the storybook and call the show function inside?