Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SASS for components style in Angular 2?

In Angular 2 when we define a component we can specify a styleUrls property to the decorator which points to a set of stylesheets to be applied to the component:

@Component({
    selector: 'the-app'
    templateUrl: 'templateFile.html',
    styleUrls: ['componentStyles.css', 'moreComponentStyles.css']
})
export class TheAppComponent {}

Now, what if I want to write these styles with SASS?

I know I would need to use Gulp or Grunt to transpile the SCSS stylesheets to plain CSS. But this makes me confused on how we would correctly point Angular to the correct stylesheets.

How could I organize this workflow of using SASS with Gulp/Grunt together with Angular 2? How to use SASS to write the Angular 2 components styles?

like image 572
user1620696 Avatar asked Jul 11 '16 18:07

user1620696


People also ask

How would you use Sass in Angular?

In the Angular CLI, all components are self-contained and so are their Sass files. In order to use a variable from within a component's Sass file, you'll need to import the _variables. scss file. One way to do this is to @import with a relative path from the component.

Can I use CSS and SCSS in Angular?

With the help of Angular CLI, you can install CSS or SCSS on your project and start working on that in a suitable way. If you are working with the CSS or SCSS in your angular project then it is very easy for you as compared to most other frameworks.

Can you use styled components in Angular?

Angular applications are styled with standard CSS. That means you can apply everything you know about CSS stylesheets, selectors, rules, and media queries directly to Angular applications. Additionally, Angular can bundle component styles with components, enabling a more modular design than regular stylesheets.


1 Answers

After following this wiki, I got some Error: Uncaught (in promise): Expected 'styles' to be an array of strings which I resolved using this answer.

Final solution is here:

home.component.ts:

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

@Component({
  selector: 'home',
  template: require('./home.component.html'),
  styles: [ String(require('./home.component.scss')) ]
})

export class HomeComponent { }

webpack.conf.js: (part of it)

  {
    test: /\.(css|scss)$/,
    loaders: [
      'style',
      'css',
      'sass',
      'postcss'
    ]
  },
like image 59
MaximeBernard Avatar answered Sep 29 '22 19:09

MaximeBernard