Fer*_*qui 4 angular-cli ng-bootstrap angular
我是 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();
}
}
Run Code Online (Sandbox Code Playgroud)
下面是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>
Run Code Online (Sandbox Code Playgroud)
但暂停不起作用,我没有收到任何错误。这是调用暂停方法的正确方法吗?请指导我。
编辑:请使用生命周期钩子,因为在组件的视图初始化后AfterViewInit调用此钩子(有关更多信息,请参阅 Angular 的生命周期钩子文档):
import { AfterViewInit, ViewChild } from '@angular/core';
// ...
export class DashboardComponent implements AfterViewInit {
@ViewChild('carousel') carousel: NgbCarousel;
ngAfterViewInit() {
this.carousel.pause();
}
}
Run Code Online (Sandbox Code Playgroud)
删除组件上NgbCarousel的提供者,因为根据文档,NgbCarousel它是一个组件而不是服务:
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
// Remove providers array
})
Run Code Online (Sandbox Code Playgroud)在元素上添加模板引用<ngb-carousel>并使用ViewChild带有模板引用的 a 作为选择器,然后调用pause实例ViewChild:
<ngb-carousel #carousel>
<!-- ... -->
</ngb-carousel>
Run Code Online (Sandbox Code Playgroud)
import { AfterViewInit, /* OnInit */, ViewChild } from '@angular/core';
// ...
export class DashboardComponent implements AfterViewInit {
@ViewChild('carousel') carousel: NgbCarousel;
ngAfterViewInit() {
this.carousel.pause();
}
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
3218 次 |
| 最近记录: |