I am trying to convert a javascript version of the following slideshow to be used in Typescript language, but I ran into an issue:
I get an error that says:
Cannot read property 'style' of undefined
It looks like it does not accept slides[this.selectedindex - 1].style.display in typescript. So I added (<HtmlElement>...) but it does not work.
I have implemented the following code:
home.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NgbCarousel, NgbSlideEvent, NgbSlideEventSource } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
title: string;
description: string;
role: Number;
public selectedindex: number = 0;
public images = ['../../assets/images/healthimage1.png', '../../assets/images/healthimage2.jpg', '../../assets/images/healthimage3.jpg'];
selectImage(index: number) {
console.log("Index: " + index);
this.selectedindex = index;
console.log("Selected Index: " + this.selectedindex);
}
showSlides() {
let i;
let slides = document.getElementsByClassName("mySlides");
let dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
(<HTMLElement>slides[i]).style.display = "none";
}
this.selectedindex++;
if (this.selectedindex > slides.length) { this.selectedindex = 1 }
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
(<HTMLElement>slides[this.selectedindex - 1]).style.display = "block";
dots[this.selectedindex - 1].className += " active";
setTimeout(this.showSlides, 2000);
}
constructor(
private activatedRoute: ActivatedRoute,
private router: Router) {
this.role = 1;
}
ngOnInit() {
this.showSlides();
}
}
home.component.html
<div *ngIf="images">
<div class="mySlides slideshow-container">
<img *ngFor="let image of images; let i=index"
[src]="image"
[ngClass]="{'image-active': selectedindex == i}">
<div style="text-align:center; display:inline-block;" *ngFor="let dot of images; let i=index">
<span class="dot"
(click)="selectImage(i)"
[ngClass]="{'active': selectedindex == i}">
</span>
</div>
</div>
</div>
css:
.slideshow-container {
max-width: 1200px;
position: relative;
margin: auto;
text-align:center;
}
.slideshow-container img{
display: none;
}
.slideshow-container img.image-active {
display: block;
width: 100%;
}
/* The dots/indicators */
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}