• info@happli.be

Tag Archive Angular

Angular 2 – ngx-datatable – ViewEncapsulation

To me, switching from AngularJS to Angular 2 is not as simple as one would think.

It’s still a bit unclear to me as how webpack gathers every dependency. I learn a bit more about it every time I code in Angular. Last challenge I faced was integrating a datatable component, namely ngx-datatable ( and check out their demo), in an Electron App (built using Angular 2 for a customer).

I’ve tried first adding the required CSS to the webpack.config.js class (I had to eject the config and now I build my app using “npm run…”). No luck.
I then managed to pack everything in the generated bundles by including the relevant styleUrls in my app.component.ts:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css',
     "../../node_modules/@swimlane/ngx-datatable/release/index.css", 
      "../../node_modules/@swimlane/ngx-datatable/release/themes/material.css",
      "../../node_modules/@swimlane/ngx-datatable/release/assets/icons.css"
    ],
  })

With these styles referenced, everything got bundled (you can check that with the developers tools when your app is started). Still I couldn’t get the styles to apply in one of the components (app.clients.ts) of my app.

It’s because of the view encapsulation. For more info, read https://github.com/AngularClass/angular-starter/wiki/How-to-include-SCSS-in-components and https://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html.

By overwriting the default view encapsulation, styles get applied globaly. So, the styles referenced in app.component.ts are applied to the app’s other components (e.g. app.clients.ts mentioned earlier). The snippet below shows the option usage.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css',
     "../../node_modules/@swimlane/ngx-datatable/release/index.css", 
      "../../node_modules/@swimlane/ngx-datatable/release/themes/material.css",
      "../../node_modules/@swimlane/ngx-datatable/release/assets/icons.css"
    ],
   encapsulation: ViewEncapsulation.None
  })

After that, the table styles were applied to the ngx-datatable used in the app.clients.ts component.