簡體   English   中英

angular2完成模板渲染后執行javascript / jquery代碼

[英]Execute javascript/jquery code after angular2 finish template rendering

我已經嘗試過這兩種方法-

ngAfterViewInit()或ngAfterContentInit()

這是我的代碼-

 import { Component, OnInit } from '@angular/core'; import { HomepageService } from '../services/homepage.service'; declare var $: any; @Component({ selector: 'app-detailpage', templateUrl: './detailpage.component.html', styleUrls: ['./detailpage.component.css'] }) export class DetailpageComponent implements OnInit { public errorMessage; public productdata; public title; public address; public old_price; public discount; public provider; public image; public description; public merchant; public new_price; constructor(protected HomepageService: HomepageService) { } ngOnInit() { this.HomepageService.getdetail() .then( data => { //console.log(data); // let topdeals = <any>data ; this.productdata = <any>data; this.title = this.productdata.title; this.address = this.productdata.address; this.old_price = this.productdata.old_price; this.discount = this.productdata.discount; this.provider = this.productdata.provider; this.image = this.productdata.image; this.description = this.productdata.description; this.merchant = this.productdata.merchant; this.new_price = this.productdata.new_price; }, error => { this.errorMessage = <any>error ; //alert(this.errorMessage.message); }); } ngAfterViewInit() { var owl = $('.gallery .owl-carousel'); owl.owlCarousel({ loop: true, items: 1, thumbs: true, thumbImage: true, thumbContainerClass: 'owl-thumbs', thumbItemClass: 'owl-thumb-item' }); } } 

在我的html模板中,我將圖像變量傳遞給owl-carousel-

問題是我的jquery代碼在正確顯示角度2頁面之前就已執行。 我的其他jquery腳本也遇到相同的問題。 我不知道如何在角度2中完全呈現頁面之前停止執行我的自定義jquery代碼。

正在工作的小伙子這個答案中搶走了。 組件具有以下設置:

import { Component, Input, ElementRef, HostBinding } from '@angular/core';
import $ from 'jquery';
import 'owl-carousel';

@Component({
  selector: 'owl-carousel',
  template: `<ng-content></ng-content>`
})
export class OwlCarousel {
  @HostBinding('class') defaultClass = 'owl-carousel';
  @Input() options: object;

  $owlElement: any;

  defaultOptions: any = {};

  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    // use default - empty
    // for (var key in this.options) {
    //   this.defaultOptions[key] = this.options[key];
    // }
    this.$owlElement = $(this.el.nativeElement).owlCarousel(this.defaultOptions);
  }

  ngOnDestroy() {
    this.$owlElement.data('owlCarousel').destroy();
    this.$owlElement = null;
  }
}

或者,您可以使用ng2-owl-carousel

兩者都有由nativeElement而不是選擇器傳遞的DOM節點,所以也許這就是問題。

//use this
this.$owlElement = $(this.el.nativeElement)
// instead of this
var owl = $('.gallery .owl-carousel');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM