2017-07-26 61 views
0

我試圖從一個角4控制器調用一個jquery函數,當一個異步函數完成時,但我找不到如何。從控制器Angular4調用jQuery函數

我的控制器:

import { Component, OnInit, ViewEncapsulation } from '@angular/core'; 
import { MyService } from '../my.service'; 

declare var $: any; 

@Component({ 
    selector: 'slider', 
    encapsulation: ViewEncapsulation.None, 
    templateUrl: './slider.component.html', 
    styleUrls: ['./slider.component.css'] 
}) 
export class SliderComponent implements OnInit { 

    banners: Promise<String[]>; 

    ngOnInit(): void { 
    this.banners.then(function(result) { 
      // HERE MUST BE MY CODE FUNCTION 
    }); 
    } 

    constructor(private myService: MyService) { 
     this.banners = this.myService.getBanners(); 

    } 
} 

而且我的模板:

<div id="slider1_container" style="position: relative; margin: 0 auto; width:600px; height:300px; left:0px; top:0px;"> 

     <!-- Slides Container --> 
     <div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 600px; height: 300px; 
      overflow: hidden;"> 
      <div *ngFor="let b of banners | async"> 
       <img u="image" src="{{ b }}" /> 
      </div> 
     </div> 

     <!-- Trigger --> 
     <div class="slideshow-block"> 

      <div style="margin: 0 4px; display: none; "> 
       <input id="stTransitionName" readonly type="text" style="width:200px;height:22px;" /> 
      </div> 
      <div style="display: none; margin: 0 4px;"> 
       <input id="stTransition" readonly type="text" style="width:100%;height:22px;" /> 
      </div> 

      </div> 
    </div> 

當我所有的橫幅被載入我需要調用一個jquery功能,使移動效果。之前,只有HTML和jQuery我調用了函數window.ready函數,但現在這是無用的,因爲它是一個異步函數。

謝謝。

+0

你不能use'window.ready'它不具備的角度。 –

+0

https://angular.io/api/core/AfterViewInit – onetwo12

回答

0

///<reference path="../typings/jquery/jquery.d.ts" /> 
 

 
import {Component, AfterViewInit} from 'angular2/core'; 
 

 
@Component({ 
 
    selector: 'your-app', 
 
    templateUrl: './app.component.html' 
 
}) 
 

 
export class AppComponent implements AfterViewInit { 
 
    ngAfterViewInit() { 
 
    // Your jQuery code goes here 
 
    $('#yourElement').text("Hello! ^_^"); 
 
    } 
 
}

+0

AfterViewInit函數可以,但我需要通過名稱調用函數,例如:我聲明瞭'function hello(){alert('hello!') ; }'但是在控制器中,我需要通過它的名字'hello();'來調用它 – Drako

相關問題