Guebli Mohamed Abdessamed Guebli Mohamed Abdessamed - 1 month ago 16
CSS Question

Why there's an array of strings instead of only one string in angular2 styles?

I'm trying to learn Angular2, but i'm little bit confused about Component styles, in the component decorator we can specify the styles to apply them to our component, there are two ways to do this :

1- We can specify the css file in styleUrls property which is an array of strings, this is logic to me, because we might have multiple css files

@Component({
selector: 'users-list',
templateUrl: 'app/users-list.template.html',
styleUrls: ['style1.css', 'style2.css']
})


2- We can write our style in the styles property which is an array of strings too, this is where i'm getting confused!! i mean why styles property is an array of strings ? why it's not just a single string !

@Component({
selector: 'users-list',
templateUrl: 'app/users-list.template.html',
styles: [
`
.glyphicon{
cursor: pointer;
}
`
]
})


In the official documentation of Angular2 they didn't say why they put an array of strings there instead of one string ! can anyone explain me!!

Answer

All of the CSS strings provided in the styles array will be applied to the component in combination. At first glance, this might sound useless, but it comes in handy if you want to mix multiple styles that aren't all hard-coded to your component. For example:

import commonStyles from "./commonStyles";

@Component({
    selector: 'users-list',
    templateUrl: 'app/users-list.template.html',
    styles: [
        ".glyphicon { cursor: pointer; }",
        commonStyles.background // This string of style rules gets applied too!
    ]
})

EDIT: To answer the questions in the comments:

commonStyles in this case would just be a normal JavaScript object containing CSS strings:

export default {
    background: "div { background-color: #00FF00; }"
};

And an advantage of doing things this way is that your application doesn't have to make additional HTTP requests to go get styleUrls (that said, I'm not familiar enough with Angular 2 to say whether or not this makes a tangible difference).