Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call child component inside slider in angular

I have created this slider

Working link :
https://stackblitz.com/edit/angular-ivy-gcgxgh?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html

HTML Component :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="slideshow-container">
  <ng-container>
    <div class="mySlides animated fadeInRight">Slide 1</div>
    <div class="mySlides animated fadeInRight">Slide 2</div>
  </ng-container>
</div>
<button class="btn ansbtn" (click)="plusSlides(-1)">Previous</button>
<button class="btn ansbtn" (click)="plusSlides(1)">Next</button>

i have to call child component inside slider like

<ng-container *ngFor="let o of list; let i=index">
<child-component-1 *ngIf="i==0"> </child-component-1>
<child-component-2 *ngIf="i==1"> </child-component-2>
..
<child-component-n *ngIf="i==n"> </child-component-n>
</ng-container>

Getting this error on click of next button :

ERROR Error: Cannot read properties of undefined (reading ‘className’)

Any solution to call child component inside slider and fix the error, Thanks

>Solution :

you have this code on your stackbitz:

var dots = this.elem.nativeElement.querySelectorAll('.dot');

and there are no elements with a "dot" class in your templates.

so when you do this:

dots[this.slideIndex - 1].className += ' active';

the value of of dots[this.slideIndex - 1] is undefined;

this then gives you the error

Cannot read properties of undefined (reading ‘className’)

To fix it, my suggestion is for you to never use a querySelectorAll in any of your angular code…

I will assume you have a variable in your actual component which is some sort of array which generates elements with this "dot" class.
so when clicking the button, you should manipulate this array variable, and not do a query on the template for its results.

The ideal angular flow is

  1. modify the data in the component
  2. all the affected templates are updated

hopefully this helps you progress!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading