簡體   English   中英

Angular/ng-bootstrap - 使用當前幻燈片更改進度條

[英]Angular/ng-bootstrap - Change Progressbar with current slide

我的目的是在每張幻燈片上更改進度條的寬度。 我目前正在使用引導程序提供的進度條。 到目前為止,我正在為每張幻燈片調用 HTML 中的事件。 此事件獲取有關幻燈片的以下信息:

Console:
{prev: "ngb-slide-0", current: "ngb-slide-1", direction: "left"}


進度條從 currentSlide (app.component.ts) 中獲取有關寬度的信息,它工作正常:

<div class="progress">
    <div class="progress-bar" role="progressbar" [style.width.%]="currentSlide"></div>
  </div>


到目前為止的打字稿進展:

export class AppComponent {

  public currentSlide: number;

  images = ['assets/images/image1.jpg', 'assets/images/image2.jpg', 'assets/images/image3.jpg'];

  changeProgress(slide: any): void {
    console.log(slide);
  }
}


我的解決方案路徑:

if current: ngb-slide-0 then currentSlide = 33,33
if current: ngb-slide-1 then currentSlide = 66,66 
if current: ngb-slide-2 then currentSlide = 100

如何將這些詞轉化為代碼?
提前致謝,蒂姆



其余的 html(滑塊示例):

<div class="container">
  <div class="row">
    <div class="col-12">
      <ngb-carousel *ngIf="images" (slide)="changeProgress($event)">
        <ng-template ngbSlide>
          <img [src]="images[0]" alt="First slide">
        </ng-template>
        <ng-template ngbSlide>
          <img [src]="images[1]" alt="Second slide">
        </ng-template>
        <ng-template ngbSlide>
          <img [src]="images[2]" alt="Third slide">
        </ng-template>
      </ngb-carousel>
    </div>
  </div>
</div>

創建一個保存幻燈片中當前進度百分比的變量,並在您觸發 changeProgress 方法時更改該值並將該百分比綁定到您的進度條,如下所示:

<div class="progress-bar active" role="progressbar" [style.width.%]="currentPercentage"
             [attr.aria-valuenow]="currentPercentage" aria-valuemin="0" aria-valuemax="100">{{this.currentPercentage}}%</div>

在你的組件中它應該是這樣的

export class AppComponent {

  public currentSlide: number;
  public currentPercentage: number;

  images = ['assets/images/image1.jpg', 'assets/images/image2.jpg', 'assets/images/image3.jpg'];

  changeProgress(event: any): void {
    this.currentSlide = Number(event.current.substring(10));//10 because you want to remove the string 'ngb-slide-' and get only the selected image
    this.currentPercentage = this.currentSlide / this.images.length * 100;
  }
}

希望這可以幫助! 就像這樣,您將來可以向幻燈片放映添加更多圖像並擁有動態代碼(我建議使用 ng-For 來顯示輪播的所有 ng-模板)

試試這個代碼:

// Add the caroussel to you component class, so you can access the slides array
@ViewChild(NgbCarousel) ngbCarousel;

....

changeProgress(slide: any): void {
    // Find the current slide index.
    let slideIndex = this.ngbCarousel.slides._results.findIndex( elem => {
      return elem.id == slide.current;
    });

    // Convert it to a percentage
    this.currentPercentage = (slideIndex + 1) / this.images.length * 100;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM