2016-07-29 4 views
2

ボタンをクリックしなくてもJQuery関数を実行できるようにするには、いくつかのヘルプを使用できます。今すぐクリックするボタンがある場合にのみ機能するので、JQueryが起動します。Angular2 JQuery、document.ready関数の作り方

コード

declare var jQuery: any; 

@Component({ 
selector: 'home-component', 
providers: [], 
moduleId: module.id, 
encapsulation: ViewEncapsulation.None, 
templateUrl: 'home.component.html', 
styleUrls: ['home.component.css'], 
directives: [BannerComponent], 
}) 

export class HomeComponent implements OnInit { 

    constructor(public productService: ProductService, private elref: ElementRef) { 

    } 

    ngOnInit(): any { 
     console.log("jQuery here"); 
     jQuery(this.elref.nativeElement).find('button').on('click', function()   { 
      jQuery('#owl-example').owlCarousel(); 
     }); 
    } 

} 

このコードは、コンポーネントの内部にOFCれます。ボタンを見つけ、クリックするとjQuery関数が実行されます。 ngOnInitが(いずれかのボタンをクリックせずに)と呼ばれている

jQuery('#owl-example').owlCarousel(); 

火災:私が欲しいもの

はこのラインを作ることです。そうするために、私はjQueryのを実装する必要があります。

$(document).ready(function() { } 

ここでの問題は、それは私がこれまで試してみましたが、このコードの平和です:)動作しないということである。

ngOnInit(): any { 
    console.log("jQuery here"); 
    jQuery(this.elref.nativeElement).ready(function() { 
     jQuery('#owl-example').owlCarousel(); 
    }); 
} 

誰かがことを願って助けて。

+1

'jQuery( '#owl-example')。owlCarousel();'このようなことは絶対にしないでください。 – dfsq

+0

なぜそれをしないのですか? – Mikkel

+1

CSSセレクタをハードコーディングしたので、柔軟性がありません。 – dfsq

答えて

7

ngOnInitと同じコンポーネント内にあるので、ngOnInitにid #owl-exampleの要素はまだ存在しません。あなたはngAfterViewInit機能を使用する必要があります。

ngAfterViewInit(): void { 
    jQuery('#owl-example').owlCarousel(); 
} 

あなたは、あなたのコンポーネント内の任意の要素が文書内に存在することを確認することができます。

+0

作品..あなたはそれを行うことができるとは知らなかった...かなり簡単に、あなたの迅速な助けをありがとう。 – Mikkel

+0

@Mikkelようこそ、幸せなコーディング;) – PierreDuc

2

あなたは、私はそれをしなかったし、それが動作

ngAfterViewInit(){  
    jQuery('#owl-example').owlCarousel(); 
} 
2

ngAfterViewInitフック以内にこのコードを書くことができます!

import { Component, OnInit, AfterViewInit } from '@angular/core'; 

declare var jQuery: any; 

@Component({ 
    selector: 'app-banners', 
    templateUrl: './banners.component.html', 
    styleUrls: ['./banners.component.css'] 
}) 
export class BannersComponent implements AfterViewInit { 

    ngAfterViewInit(): void { 
    jQuery('.slider').slider({full_width: true}); 
} 


    constructor() { } 

    ngOnInit() { 


    } 

} 
関連する問題