Search code examples
angular-materialstorybook

Add Angular Material to Lib in Nx Monorepo


I am trying to view a story of an Angular Material Button. However, in the story, the button does not have any styles. I imported angular material using : ng add angular/material and these ara my files for my component :

This is the html file :

<button mat-button color="primary">Button Material</button>

This is the module of my lib :

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Route } from '@angular/router';
import { ElementComponent } from './element/element.component';
import {MatButtonModule} from '@angular/material/button';
import { MaterialComponent } from './material/material.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';


export const plateRoutes: Route[] = [];

@NgModule({
  imports: [CommonModule, RouterModule,BrowserAnimationsModule, MatButtonModule],
  declarations: [
    ElementComponent,
    MaterialComponent,

  ],
})
export class PlateModule {}

This is the component story :

enter image description here

As you can see the style does not apply to the mat button...


Solution

  • In your MaterialComponent you have to import the material module of Button

    import { MatButtonModule } from '@angular/material/button';
    import { Meta, moduleMetadata, Story } from '@storybook/angular';
    
    import { ButtonComponent } from './button.component';
    
    export default {
      title: 'button',
      component: ButtonComponent,
      decorators: [
        moduleMetadata({
          imports: [MatButtonModule],
        }),
      ],
    } as Meta<ButtonComponent>;
    

    And after this you will need to add the style in the storybook and build-storybook steps of the storybook

    
    {
    ...
    "storybook": {
       ...
       "options": {
         "styles": [
           // the style that you should import
           "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css"
         ]
       },
     "build-storybook": {
       ...
       "options": {
         "styles": [
           // the style that you should import
           "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css"
         ]
       },
     }
    ...
    }