[Fixed] How to get value from carousel which is active?

Issue

I am using reactive forms, when submitting a form I want to send the carousel’s active item as a value.
how can I achieve that?

here is my stackblitz

.ts

this.formGroup = this._formBuilder.group({
  formArray: this._formBuilder.array([
    this._formBuilder.group({
      firstName: ["", Validators.required],
      lastName: ["", Validators.required],
      Age: ["", Validators.required]
    })
  ])
});

.html

  <input matInput formControlName="firstName" type="text" class="form-control" placeholder="First Name" required>
  <input matInput formControlName="lastName" type="text" class="form-control" placeholder="Last Name" required>

  <p>Select Age</p>
  <carousel height="100%" width="120" cellsToShow="1" overflowCellsLimit="3" id="age">
    <div class="carousel-cell" *ngFor="let year of years">
      {{year.year}}Years
    </div>
  </carousel>
  <button style="margin-top: 4rem;" mat-button matStepperNext (click)="onSubmit()" class="next">Submit <i class="fas fa-chevron-right"></i></button>

Solution

In your .ts file add a new property named myCarousel with a @ViewChild decorator like below:

@ViewChild("myCarousel") myCarousel: CarouselComponent;

Now, add a reference to the myCarousel in your html file like below:

<carousel #myCarousel height="100%" width="120" cellsToShow="1" overflowCellsLimit="3" id="age">
    <div class="carousel-cell" *ngFor="let year of years">
       {{year.year}}Years
    </div>
</carousel>

Next in your onSubmit method you could get the current activate slide by using this.myCarousel.slideCounter like below

onSubmit() {
  console.log(this.formGroup.value);
  console.log(this.myCarousel.slideCounter + 1)
}

The slideCounter property start its counting from 0 and that’s why I have added +1
I have tested it in stackblitz. Let me know if you face any issue

Leave a Reply

(*) Required, Your email will not be published