繁体   English   中英

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

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

我尝试通过ng-content包含组件中包含的css for children元素。 它似乎尚未在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 !!!
}

您可以使用/deep/ (不建议使用)或>>>::ng-deep选择器:

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

例如:

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

请注意, >>>似乎不适用于基于angular-cli的项目。

将类应用于将要呈现的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;
}

这在我的项目中对我有用。

暂无
暂无

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

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