Is there a way to use css in ng-content inside an Angular2 component?
Asked Answered
A

2

16

I tried to include css for children element included in a component via ng-content. It seems to be not implemented yet in Angular 2 or maybe someone has got a solution except to put css in a general stylesheet ?

app.component.ts

<comp-parent>
  <comp-child></comp-child>
</comp-parent>

compParent.component.html

<div class="wrapper">
  <ng-content></ng-content>
</div>

compParent.component.css

.wrapper > comp-child {
   margin-right: 5px; <-- Not applied !!!
}
Albacore answered 23/2, 2017 at 12:40 Comment(1)
<comp-child> is your component. Place the HTML element instead. For example - your <comp-child> will be replaced by the template which has another component <ng-component>. Use the HTML element that will actually render in the DOM.Allergic
U
13

You can use /deep/ (deprecated) or >>> or ::ng-deep selector:

https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep

E.g.:

.wrapper ::ng-deep comp-child { ... }

Note that >>> seems to not work for projects based on angular-cli.

Unpin answered 23/2, 2017 at 16:12 Comment(2)
Actually, it seems to be work if you add :host to use /deep/.Albacore
Note that /deep/ is in deprecation status #35742222Charleton
G
-1

Apply classes to the html which is going to be rendered.

 app.component.ts
  <comp-parent>
    <comp-child></comp-child>
  </comp-parent> 

@Component({

    selector: 'comp-parent',
    template: `
        <div class="wrapper">
            <ng-content></ng-content>
        </div>
        `          
})
export class CompParent { }   

@Component({
selector: 'comp-child',
template: `
    <div class="comp-child">
        <div>
        </div>
    </div> `,
})

export class CompChild {}


/// In styles.css
.wrapper .comp-child {
    margin-left: 50px;
}

This worked for me in my project.

Galvin answered 24/2, 2017 at 6:26 Comment(1)
"... except to put css in a general stylesheet ?" ;-) . Of course, that works in styles.css.Albacore

© 2022 - 2024 — McMap. All rights reserved.