html - Angular/ng-bootstrap - เปลี่ยน Progressbar ตามสไลด์ปัจจุบัน
ความตั้งใจของฉันคือการเปลี่ยนความกว้างของแถบความคืบหน้ากับทุกสไลด์ ขณะนี้ฉันกำลังใช้แถบความคืบหน้าที่ให้โดย bootstrap จนถึงตอนนี้ฉันกำลังเรียกเหตุการณ์ใน 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>
ความก้าวหน้าของ Typescript จนถึงตอนนี้:
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
จะเปลี่ยนคำเหล่านี้ให้เป็นโค้ดได้อย่างไร?
ขอบคุณล่วงหน้า, Tim
ส่วนที่เหลือของ 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>
คำตอบ #1
สร้างตัวแปรที่เก็บเปอร์เซ็นต์ปัจจุบันของความคืบหน้าในสไลด์และเปลี่ยนค่าดังกล่าวเมื่อคุณเรียกใช้เมธอด 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-template ของคารูเซลของคุณ)
คำตอบ #2
ลองใช้โค้ดนี้:
// 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;
}
