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?
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.
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.
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.
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'
]
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With