我是 Angular 的新手,我的用户界面使用 ngbootstrap。默认情况下,我无法在暂停模式下加载 NgbCarousel。下面是我试过的代码
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgbCarousel } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'],
providers: [NgbCarousel] // add NgbCarouselConfig to the component providers
})
export class DashboardComponent implements OnInit {
constructor(private auth: AuthService, private ngbCarousel: NgbCarousel) {}
ngOnInit() {
this.ngbCarousel.pause();
}
}
下面是html文件:
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-12 col-lg-9">
<ngb-carousel>
<ng-template ngbSlide>
<img src="https://lorempixel.com/900/500?r=1" alt="Random first slide">
<div class="carousel-caption">
<h3>First slide label</h3>
<p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
</div>
</ng-template>
<ng-template ngbSlide>
<img src="https://lorempixel.com/900/500?r=2" alt="Random second slide">
<div class="carousel-caption">
<h3>Second slide label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</ng-template>
<ng-template ngbSlide>
<img src="https://lorempixel.com/900/500?r=3" alt="Random third slide">
<div class="carousel-caption">
<h3>Third slide label</h3>
<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p>
</div>
</ng-template>
</ngb-carousel>
</div>
</div>
</div>
</div>
但是暂停不起作用,我没有收到任何错误。这是调用暂停方法的正确方法吗?请指导我。
最佳答案
编辑:请使用 AfterViewInit
生命周期 Hook ,因为此 Hook 在组件的 View 初始化后 被调用(有关更多信息,请参阅 Angular 的 lifecycle hooks documentation):
import { AfterViewInit, ViewChild } from '@angular/core';
// ...
export class DashboardComponent implements AfterViewInit {
@ViewChild('carousel') carousel: NgbCarousel;
ngAfterViewInit() {
this.carousel.pause();
}
}
删除
NgbCarousel
作为您组件的提供者,因为根据 docs ,NgbCarousel
是一个组件并且不是一个服务:@Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] // Remove providers array })
在
<ngb-carousel>
上添加模板引用元素并使用ViewChild
使用模板引用作为选择器,然后调用pause
在ViewChild
上实例:<ngb-carousel #carousel> <!-- ... --> </ngb-carousel>
import { AfterViewInit, /* OnInit */, ViewChild } from '@angular/core'; // ... export class DashboardComponent implements AfterViewInit { @ViewChild('carousel') carousel: NgbCarousel; ngAfterViewInit() { this.carousel.pause(); } }
关于angular - 如何在angular 5的ngOnInit上调用NgbCarousel的pause()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48203536/