0

In Angular2, when I add a class tag on my custom Angular2 component like so:

<my-component class="someClass"></my-component>

...the styling does not get applied to the HTML. In Chrome Developer tools, when I select my-component element, the styles inspector shows that the styles are being applied, but visually, they are not. Is this normal? How do I get around that?

1
  • Post the component decorator part, please Commented Aug 10, 2017 at 9:56

3 Answers 3

4

Angular 2 use Shadow DOM, that is part of the Web Components standard and enables DOM tree and style encapsulation. Angular View Encapsulation

So if you want to style something in my-component you should write your class's in my-component class.

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

@Component({
    teamplte: '<h1 class="myClass">i am my-component</h1>',
    styles: [`
      .myClass {
         someProp: value;
      }
    `]
})

export class ConatinerComponent implements OnInit {
    constructor() { }

    ngOnInit() { }
}

but if you want to style outside you must to write your styles and classes in container component!

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

@Component({
    teamplte: '<my-component class="myClass"></my-component>',
    styles: [`
      .myClass {
         someProp: value;
      }
    `]
})

export class MyComponentComponent implements OnInit {
    constructor() { }

    ngOnInit() { }
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to pass any thing like className then use bindings:

@Component({
 selector: 'my-component',
 template: template,
 styleUrls: ['app/components/nav-bar/nav-bar.style.css'], // or you can add explicit style,
bindings:{
  className: '<'
}  
})

HTML

 <my-component class-name="someClass"></my-component>

Hope this will help you.

1 Comment

Angular2 throws an error when I did this: Argument of type '{ selector: string; templateUrl: string; styleUrls: string[]; bindings: { className: string; }; }' is not assignable to parameter of type 'Component'. Object literal may only specify known properties, and 'bindings' does not exist in type 'Component'.
0

Why do you use this method? All you need is to add some styles to your my-component.

CSS

my-component {
   background: black;
   text-align: center;
 }

And of course, in your component to add html code

1 Comment

Actually, this doesn't work for me on Chrome (or any other browser). I get the same problem as is my original question: Developer tools tells me the style is there, but visually, it's not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.