简体   繁体   中英

Angular 4 + JavaScript - Simple slideshow didn't work

So I put the <script> inside a single component, StartComponent .

StartComponent is in a <router-outlet> which inside Root or AppComponent.

I've tested this working in a single index.html file (Non-Angular or Non-Component based). But I have no idea why it didn't work in Angular 4 (Component based)

( StartComponent ) StartComponent

var i = 0;
var images = [];
var time = 1000;

// Image list
images[0] = 'assets/pictures/kapal02.jpg';
images[1] = 'assets/pictures/kapal01.jpg';
images[2] = 'assest/pictures/truck.jpg';

// Function
function changeImage() {
    document.getElementById('slideshow').src = images[i];

    if(i < images.length - 1) {
      i++;
    }
    else {
      i = 0;
    }

    setTimeout("changeImage()", time);
}

window.onload = changeImage;


<img id="slideshow" src="assets/pictures/kapal02.jpg">

I have created this simple plunker on how to do this in angular2. Please have a look at home.component file. This will give you an idea on how to tackle this in angular2 way.

Checkout this Plunker

Code for home component as below

export class HomeComponent implements OnInit {
  urlVariable:string;
  images:Array<any>
  ngOnInit() {
        var i = 0;
        this.images = [];
        var time = 1000;

        // Image list
        this.images[0] = 'http://i64.tinypic.com/2czam2x.jpg';
        this.images[1] = 'http://i63.tinypic.com/2czanp2.jpg';
        this.images[2] = 'http://i63.tinypic.com/2czaq8k.jpg';

        this.urlVariable = this.images[0];
  }

  setImage(index:number){
     this.urlVariable = this.images[index];
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM