为什么本地元素本地引用在ngx-slick-carousel中不起作用

时间:2019-05-09 05:19:06

标签: angular

我只想检查当前正在显示哪个幻灯片,以便可以向当前活动的图像中添加一些文本动画。在ngx滑块中,它将平滑活动或当前课程添加到当前活动的滑块。

我放置了一个本地galleryOne,并尝试使用viewchild和element ref对其进行检查,但它给出了错误

TypeError: Cannot read property 'classList' of undefined

如果我在ngx-slick-carousel选择器之外执行操作,则没有问题。

<ngx-slick-carousel class="carousel"  class="lazy slider" 
          #slickModal="slick-carousel" #galleryOne [config]="slideConfig"
          >
            <div ngxSlickItem *ngFor="let slide of slides" class="slide">
              <h1>{{slide.txt}}</h1>
              <figure><img src="{{slide.img}}" width="509" alt="responsive websites" class="img-responsive"></figure>
            </div>
          </ngx-slick-carousel>

打字稿

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
    export class HomeComponent implements OnInit {
      @ViewChild('galleryOne') galleryOne: ElementRef;
     slides = [
        {img: "theme/images/home01.jpg", txt: 'dsfsdfsdfsdfsdf'},
        {img: "theme/images/home02.jpg", txt: 'sdddddddddddddddddd'},
        {img: "theme/images/home03.jpg", txt: 'dsfdsffffffffffffffffffsfsdf'}
      ]
      slideConfig = {autoplay: true,"slidesToShow": 1, "slidesToScroll": 1, speed:800, "autoplaySpeed": 3000, cssEase: 'cubic-bezier(0.250,  0.060, 0.050, 0.040)'};

     ngOnInit() {
        console.log(this.galleryOne.nativeElement.classList.hasClass('slick-active'));

1 个答案:

答案 0 :(得分:0)

类似的事情应该起作用:
仅在AfterViewInit生命周期挂钩中正确定义galleryOne ElementRef

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
    export class HomeComponent implements OnInit, AfterViewInit {
      @ViewChild('galleryOne') galleryOne: ElementRef;
     slides = [
        {img: "theme/images/home01.jpg", txt: 'dsfsdfsdfsdfsdf'},
        {img: "theme/images/home02.jpg", txt: 'sdddddddddddddddddd'},
        {img: "theme/images/home03.jpg", txt: 'dsfdsffffffffffffffffffsfsdf'}
      ]
      slideConfig = {autoplay: true,"slidesToShow": 1, "slidesToScroll": 1, speed:800, "autoplaySpeed": 3000, cssEase: 'cubic-bezier(0.250,  0.060, 0.050, 0.040)'};

     ngOnInit() {

     }

     ngAfterViewInit() {
        console.log(this.galleryOne.nativeElement.classList.hasClass('slick-active'));
     }
}