我正在使用角度4和ng-bootstrap轮播。 我想在加载时跳转到最后一张幻灯片,尝试使用activeId,但这没有帮助
<ngb-carousel [activeId]="1">
答案 0 :(得分:5)
代码中的更改
<!--check the template reference variable-->
<ngb-carousel #myCarousel="ngbCarousel" >
<!-- is "id={{i}} -->
<ng-template ngbSlide *ngFor="let item of data;let i = index" id="{{i}}">
<h1>{{item}}</h1>
</ng-template>
</ngb-carousel>
您的.ts必须实现onInit并使用ViewChild
import { Component, OnInit, ViewChild} from '@angular/core';
import {NgbCarousel,NgbCarouselConfig} from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'ngbd-carousel-basic',
templateUrl: 'src/carousel-basic.html',
providers: [NgbCarouselConfig]
})
export class NgbdCarouselBasic implements OnInit {
//reference to "myCarousel"
@ViewChild('myCarousel') myCarousel: NgbCarousel;
private data = ["Slide 1","Slide 2","Slide 3"]
//I prefered use private for all injected component
constructor(private config: NgbCarouselConfig) {
this.config.interval = 10000;
this.config.wrap = false;
this.config.keyboard = false;
}
ngOnInit() {
this.myCarousel.activeId='2'; //<--use this, begans 0
}
}
答案 1 :(得分:0)
如果有人想知道activeId
为什么对您不适合,
然后选择版本:
"@ng-bootstrap/ng-bootstrap": "^4.0.4", // or above
您可以使用select()
提供的NgbCarousel
方法。
假设ID为slideId-1
,然后这样做
this.myCarousel.select('slideId-1');
在查看文件中:
<!--check the template reference variable-->
<ngb-carousel #myCarousel="ngbCarousel" >
<!-- is "id={{i}} -->
<ng-template ngbSlide *ngFor="let item of data;let i = index" id="slideId-{{i}}">
<h1>{{item}}</h1>
</ng-template>
</ngb-carousel>
.ts文件中的
:import { Component, OnInit, ViewChild} from '@angular/core';
import {NgbCarousel} from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'ngbd-carousel-basic',
templateUrl: 'src/carousel-basic.html'
})
export class NgbdCarouselBasic implements OnInit {
//reference to "myCarousel"
@ViewChild('myCarousel') myCarousel: NgbCarousel;
items: object[];
constructor() {}
ngOnInit() {
this.loadMyItems(); // load items from an API
}
loadMyItems() {
...
yourService.getItems().subscribe(
response => {
this.items = response.data;
setTimeout(() => { this.scheduleCarousel.select('slideId-1') }); // if you are getting `.select() of undefined` error.
}
.....
}
}
在这里,我提供了一个API示例,如果您有静态数据,则可以按照上述答案进行操作。
答案 2 :(得分:0)
无需对 ts 文件进行任何更改。这里需要单引号:
<ngb-carousel [activeId]="'1'">
正如其他人提到的,您需要在模板中执行以下操作。
<ng-template ngbSlide *ngFor="let item of data;let i = index" id="{{i}}">