2016-12-17 108 views
0

我想添加一段jQuery代码到我上线的组件。 Specifically this.添加JQuery插件到Angular 2组件

我已经在代码中实现了HTML和CSS,但是我有麻烦让jQuery加载。我在html部分的底部使用了<script>标签,但它似乎不起作用。有任何想法吗?

+0

你是否在使用材料的时候可以用制表符复制这些材料,并且都是有角度的。你是仅仅为这个插件使用jquery,还是在你的应用中使用其他的东西? –

+0

@JJB我现在只是在我的应用程序中使用它。 – Lewis

+0

你在使用TypeScript吗?你在使用SystemJS还是Webpack? –

回答

0

您可以使用ViewChild装饰器来获取HTML内容的引用,然后在ngAfterViewInit生命周期钩子中使用该引用。您可以在组件内部使用引用,但是如果想要使用任何类型的初始化jQuery然后ngAfterViewInit是一个合适的地方做到这一点。

例如,如果HTML模板具有以下代码。

<!-- my-component.html--> 

<section class="cd-hero"> 
    <ul class="cd-hero-slider"> 
     <li class="selected"> 
      <div class="cd-full-width"> 
       <h2><!-- title here --></h2> 
       <p><!-- description here --></p> 
       <a href="#0" class="cd-btn"><!-- btn text here --></a> 
      </div> <!-- .cd-full-width --> 
     </li> 

     <!-- othe slides here --> 

    </ul> <!-- .cd-hero-slider --> 

    <div class="cd-slider-nav" #cdSliderNav > 
     <nav> 
      <span class="cd-marker item-1"></span> 

      <ul> 
       <li class="selected"><a href="#0">Intro</a></li> 
       <li><a href="#0">Tech 1</a></li> 
       <!-- other navigation items here --> 
      </ul> 
     </nav> 
    </div> <!-- .cd-slider-nav --> 
</section> <!-- .cd-hero --> 

然后我可以在我的组件得到cdSliderNav变量的引用,如下所示。

//myComponent.ts 

declare var jQuery: any 

@Component({ 
    selector:'my-component', 
    templateUrl:'my-component.html', 
    styleUrls:['my-component.css'] 
}) 
export class MyComponent implements AfterViewInit{ 
    @ViewChild('cdSliderNav') cdSliderNav:ElementRef; 

    ngAfterViewInit() { 
     jQuery(this.cdSliderNav.nativeElement).on('click', 
     event => { 
        //Handle click event here.. 
        console.log(event); 
       } 
    ) 
    } 
} 

,你也可以声明jQuery的变量中的分型文件,如果你不想单独声明它为每个组件file.And确保您已包括您index.html文件中的jQuery文件。

一旦我们获得了对主div的引用,那么我们可以使用jQuery方法来选择它的子节点或者使用jQuery来做我们想做的任何事情。为前。在我的cdSliderNav里面选择li元素我可以使用find()方法。

jQuery(this.cdSliderNav.nativeElement).find('li') 

我希望这会有所帮助。