Angular 4 + JavaScript - 简单的幻灯片显示无效

时间:2017-05-01 05:44:14

标签: javascript html angular

所以我把<script>放在一个组件中, StartComponent

StartComponent 位于 Root 或AppComponent内的<router-outlet>

我已经在单个index.html文件(非角色或非基于组件)中对此进行了测试。但我不知道为什么它在Angular 4(基于组件)

中不起作用

start.component.html 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">

1 个答案:

答案 0 :(得分:0)

我已经创建了这个简单的plunker如何在angular2中执行此操作。请看一下home.component文件。这将让您了解如何以angular2方式解决这个问题。

Checkout this Plunker

家庭组件代码如下

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];
  }
}