gpt4 book ai didi

angular - 如何在angular 5的ngOnInit上调用NgbCarousel的pause()函数

转载 作者:行者123 更新时间:2023-12-02 00:38:34 25 4
gpt4 key购买 nike

我是 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();
}
}

  1. 删除 NgbCarousel作为您组件的提供者,因为根据 docs , NgbCarousel是一个组件并且不是一个服务:

    @Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.css']
    // Remove providers array
    })
  2. <ngb-carousel> 上添加模板引用元素并使用 ViewChild使用模板引用作为选择器,然后调用 pauseViewChild 上实例:

    <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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com