Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How modify CSS of ng-bootstrap carousel using Angular 2

recently, I have tried to modify the class "carousel-item" inside ng-bootstrap carousel component. However, I found that I need to add "encapsulation: ViewEncapsulation.None" in the metadata. Using this solution would also change the css on the other carousel component. Is there any other solution to modified the css class inside ng-bootstrap carousel component.

Here is my code:

my ts file:

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() { }
}

my View "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>

And my style sheet "carousel.component.scss":

  .carousel-item.active{
    display:inline;
    img{
      width: 100%;
    }
  }
like image 225
Vincent Ho Avatar asked Dec 24 '22 18:12

Vincent Ho


1 Answers

This question has more to do with how styles encapsulation work in Angular rather than something specific to ng-bootstrap, but the short answer is that in the default style encapsulation (from https://angular.io/docs/ts/latest/guide/component-styles.html):

Component styles normally apply only to the HTML in the component's own template

Since ngb-carousel is not part of the component HTML (it is a different component altogether) you have to force styles to propagate down the components structure:

Use the /deep/ selector to force a style down through the child component tree into all the child component views. The /deep/ selector works to any depth of nested components, and it applies to both the view children and content children of the component

Translating this to your particular problem would mean that you should write:

  styles: [`
     /deep/ .carousel-item.active {
        border: solid 0.3em;
        border-color: red;
     }
  `]

Here is a live example in a plunker: http://plnkr.co/edit/7J3CItUtSua1zJ7GG1xH?p=preview

like image 191
pkozlowski.opensource Avatar answered Dec 28 '22 10:12

pkozlowski.opensource