Home > OS >  Loading SwiperComponent in appComponent Angular 13 with ViewChild
Loading SwiperComponent in appComponent Angular 13 with ViewChild

Time:06-03

I have a simple carousel in angular 13 appCoponent and i would like to stop and resume the autoplay but i am getting The swipercomponent to be undefined but it's not behind any ngif or other shadowing directive so the problem probably lays in the fact that in the documentation is only explained the API and not how it works. The code is as follows in the component:

import { Component, Pipe, PipeTransform, OnInit, ViewChild} from '@angular/core';
import { SwiperOptions} from 'swiper';
import { SwiperComponent } from 'swiper/angular';
import { EndPointService } from './end-point.service';
import { GraphSite } from './GraphSite';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
@ViewChild('swiperSlideShow') swiperSlideShow!: SwiperComponent;
endPoints:  GraphSite[] =[];

  config: SwiperOptions = {
    autoplay: {
      delay: 2000,
      disableOnInteraction: false,
      pauseOnMouseEnter: true
    },
    pagination: { 
      el: '.swiper-pagination', 
      clickable: true 
    },
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev'
   },
   spaceBetween: 30
  };

 constructor(private endPointService: EndPointService){
 };

  ngOnInit(){
   this.getEndPoints();
  };

  ngAfterViewInit(): void {
      this.swiperSlideShow.autoplay.start();
  }

  getEndPoints(){
    this.endPointService.getEndPoints().subscribe(endPoints => this.endPoints = 
endPoints);
 };

  startCarousell(){
    this.swiperSlideShow.swiperRef.autoplay.start();
  }

  stopCarousell(){
    this.swiperSlideShow.swiperRef.autoplay.stop();
  }

}

The error it throws is from ngAfterViewInit and it says that swiperSlideShow is undefined.

The template of the carousel is as follows:

<h1 >Graph Statistics</h1>
<button (click)="startCarousell" >Play</button>
<button (click)="stopCarousell" >Pause</button>
<div>
    <swiper [config]="config">
        <div >
            <iframe 
                    *ngFor="let point of endPoints"
                    [src]="point.src | safe">
            </iframe>
        </div>
        <div ></div>
        <div ></div>
        <div ></div>
    </swiper>
</div>

CodePudding user response:

Your @ViewChild binding is incorrect. The way you defined it Angular will look for a variable called swiperSlideShow which isn't present. There are two ways to fix this:

  1. Bind your swiper component to a variable: <swiper #swiperSlideShow [config]="config">
  2. Bind your ViewChild by component like this: @ViewChild(SwiperComponent) swiperSlideShow!: SwiperComponent;
  • Related