【问题标题】:Is there a way to use css in ng-content inside an Angular2 component?有没有办法在 Angular2 组件内的 ng-content 中使用 css?
【发布时间】:2017-07-13 22:49:57
【问题描述】:

我尝试通过 ng-content 为组件中包含的子元素包含 css。它似乎还没有在 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 !!!
}

【问题讨论】:

  • 是您的组件。而是放置 HTML 元素。例如 - 您的 将被具有另一个组件 的模板替换。使用将在 DOM 中实际呈现的 HTML 元素。

标签: css angular styles angular2-ngcontent


【解决方案1】:

您可以使用/deep/(已弃用)或&gt;&gt;&gt;::ng-deep 选择器:

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

例如:

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

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

【讨论】:

【解决方案2】:

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

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

【讨论】:

  • "...除了将 css 放在通用样式表中?" ;-) 。当然,这适用于 styles.css。
猜你喜欢
  • 1970-01-01
  • 2022-01-11
  • 2021-03-11
  • 2017-02-09
  • 2017-11-01
  • 2016-07-31
  • 1970-01-01
相关资源
最近更新 更多