Search code examples
typescriptelementref

Getting html value in typescript using @ViewChild()


I am using ngbSlide as following:

<ngb-carousel>
  <ng-template ngbSlide *ngFor="let item of images; let i = index">
      <img src="{{item}}"/>               
      <input type="text" #index value="{{i}}"/> 
  </ng-template>     
</ngb-carousel>

I want to know which of the three images is shown to the user at any moment. To get this value, I'm trying to use @ViewChild as following:

export class GalleryComponent {
    @ViewChild('index') index!: ElementRef;

    images: string [] = [
     "https://picsum.photos/id/700/900/500",
     "https://picsum.photos/id/1011/900/500",
     "https://picsum.photos/id/984/900/500"    
    ]        
   
    constructor() {}

    ngAfterContentChecked () {        
      console.log("index value is: ", this.index?.nativeElement.value)     
    }    
}

But the index value is once undefined, and then is always 0, however, I see the value of input is updating. Any idea what is wrong in my code? I am using angular 17.


I have followed answers to this very similar question and used @viewChild as:

    @ViewChild('index', {static: false})
    private index!: ElementRef;

but still I only get 0 as index value.


Solution

  • Template Update:

    <ngb-carousel #carousel="ngbCarousel" (slide)="onSlide($event)">
      <ng-template ngbSlide *ngFor="let item of images; let i = index" id="slide-{{i}}">
          <img src="{{item}}"/>               
      </ng-template>     
    </ngb-carousel>
    

    Component Update:

    import { Component, ViewChild, AfterViewInit } from '@angular/core';
    import { NgbCarousel } from '@ng-bootstrap/ng-bootstrap';
    
    @Component({
      selector: 'app-gallery',
      templateUrl: './gallery.component.html',
      styleUrls: ['./gallery.component.css']
    })
    export class GalleryComponent implements AfterViewInit {
      @ViewChild(NgbCarousel) carousel!: NgbCarousel;
    
      images: string [] = [
        "https://picsum.photos/id/700/900/500",
        "https://picsum.photos/id/1011/900/500",
        "https://picsum.photos/id/984/900/500"    
      ];
    
      constructor() {}
    
      ngAfterViewInit() {
        
        console.log("Initially active slide:", this.carousel.activeId);
      }
    
      onSlide(event: any) {
        console.log("Current slide index:", event.current);
        
        const currentIndex = event.current.replace('slide-', '');
        console.log("Extracted index:", currentIndex);
      }
    }