简体   繁体   English

有没有办法在Angular2组件中的ng-content中使用css?

[英]Is there a way to use css in ng-content inside an Angular2 component?

I tried to include css for children element included in a component via ng-content . 我尝试通过ng-content包含组件中包含的css for children元素。 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 ? 它似乎尚未在Angular 2中实现,或者除了将css放在一般样式表中之外,有人可能有解决方案?

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 !!!
}

You can use /deep/ (deprecated) or >>> or ::ng-deep selector: 您可以使用/deep/ (不建议使用)或>>>::ng-deep选择器:

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

Eg: 例如:

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

Note that >>> seems to not work for projects based on angular-cli. 请注意, >>>似乎不适用于基于angular-cli的项目。

Apply classes to the html which is going to be rendered. 将类应用于将要呈现的html。

 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. 这在我的项目中对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM