0

How can I use Angular 2 styles in @Component with multiple classes on the same tag?

@Component({
    styles: `.class1 .class2{background-color:red;}`
})

This generates the following css code:

.class1[<RANDOM_ANGULAR_ATTR>] .class2[<RANDOM_ANGULAR_ATTR>]{
    background-color: red; 
}

This will not select a tag defined like this:

<div class=".class1 .class2" RANDOM_ANGULAR_ATTR></div>

Is there any way to make this approach work?

2 Answers 2

1

Your styles should have the classes without a space between them. Multiple classes in the same selector must be written directly after each another – with no white space. For example:

.class1.class2 { background-color:red; }

And in order to select your object you should have the classes added like this:

<div class="class1 class2">Test css</div>

See the code below:

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

@Component({
  selector: 'my-app',
  styles: [
`
.class1.class2{background-color:red};
` ],
  template: `
<h1>My First Angular 2 App</h1>
<div class="class1 class2">Test css</div>
`
})
export class AppComponent { }

For more options see also the following blog posts (about Shadow DOM, Encapsulation Types .. any other cool things):

  1. https://scotch.io/tutorials/all-the-ways-to-add-css-to-angular-2-components

  2. http://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html

1
  • Thank you very much! Removing the whitespace indeed did the trick for me! Commented Jun 26, 2016 at 1:42
0

Have you looked at Justin Schwartzenberger's NG-Conf talk on CSS styles and the randomly generated tag? https://www.youtube.com/watch?list=PLOETEcp3DkCq788xapkP_OU-78jhTf68j&v=J5Bvy4KhIs0

potential options are to:

  1. Use a styleUrls template
  2. change encapsulation
  3. use a different class (since its only relevant to this component its ok to name something simple vs using 2)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.