如何使用Angular 2修改ng-bootstrap轮播的CSS

Vin*_* Ho 4 ng-bootstrap angular

最近,我试图修改ng-bootstrap轮播组件中的"carousel-item"类.但是,我发现我需要在元数据中添加"encapsulation:ViewEncapsulation.None".使用此解决方案还将更改另一个轮播组件上的css.是否有任何其他解决方案来修改ng-bootstrap轮播组件内的css类.

这是我的代码:

我的ts文件:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {NgbCarouselConfig} from '@ng-bootstrap/ng-bootstrap';

@Component({
  moduleId: module.id,
  selector: 'carousel',
  templateUrl: 'carousel.component.html',
  encapsulation: ViewEncapsulation.None,
  styleUrls : ['./carousel.component.scss'],
  providers: [NgbCarouselConfig]
})

export class CarouselComponent implements OnInit {
  constructor(config: NgbCarouselConfig) {
    // customize default values of carousels used by this component tree
    config.interval = 10;
    config.wrap = false;
    config.keyboard = false;
  }

  ngOnInit() { }
}
Run Code Online (Sandbox Code Playgroud)

我的视图"carousel.component.html":

<ngb-carousel>
  <template ngbSlide>
    <img src="http://lorempixel.com/900/500?r=4" alt="Random first slide">
    <div class="carousel-caption">
      <h3>10 seconds between slides...</h3>
      <p>This carousel uses customized default values.</p>
    </div>
  </template>
</ngb-carousel>
Run Code Online (Sandbox Code Playgroud)

我的样式表"carousel.component.scss":

  .carousel-item.active{
    display:inline;
    img{
      width: 100%;
    }
  }
Run Code Online (Sandbox Code Playgroud)

pko*_*rce 9

这个问题更多地与样式封装在Angular中的工作方式有关,而不是与ng-bootstrap特定的内容有关,但简短的答案是在默认样式封装中(来自https://angular.io/docs/ts/latest/guide) /component-styles.html):

组件样式通常仅适用于组件自己的模板中的HTML

由于NGB传送带不是该组件的HTML的一部分(这是一个完全不同的组件),你必须强迫风格传播下来的组件结构:

使用/ deep/selector将样式向下强制通过子组件树到所有子组件视图中./ deep/selector适用于任何深度的嵌套组件,它适用于视图子节点和组件的内容子节点

将此翻译为您的特定问题意味着您应该写:

  styles: [`
     /deep/ .carousel-item.active {
        border: solid 0.3em;
        border-color: red;
     }
  `]
Run Code Online (Sandbox Code Playgroud)

这是一个关于plunker的实例:http://plnkr.co/edit/7J3CItUtSua1zJ7GG1xH?p = preview

  • `::ng-deep` 现在比 `/deep/` 更推荐 (3认同)