Dom渲染问题ngAfterViewInit离子2

时间:2017-03-30 16:53:15

标签: angular dom ionic-framework ionic2

我是Ionic和有角度的新手。我注意到一些特殊的问题。

每当我需要访问DOM时,我都必须进行超时查询才能获得动态元素。

如果我使用ngAfterViewInit事件 - 这不起作用。

因此,例如,当尝试访问动态生成的URL时,这不起作用。

 ngAfterViewInit() {

    var that  = this;
    that.img = that.el.nativeElement.querySelector('img');
    alert(that.src);

}

然而,这将

 ngOnInit() {

      var that  = this;
      setTimeout(function () {  // still buggy need to wait for dom to load.

      that.img = that.el.nativeElement.querySelector('img');

      alert(that.src);

      }, 300);
    }

我正在使用ios模拟器,这是在Ionic组件中我尝试了以下代码,如果没有超时,它将无法正常工作。因为在没有完全加载Dom的情况下,视图中由javascript生成的url不会被注册。

import { Component, ElementRef, Input, OnInit, AfterContentInit } from '@angular/core';

    import ImgCache from 'imgcache.js';

    /**
     * This component will be in charge of caching images and use them when the app is offline
     */
    @Component({
      selector: 'lazy-img',
      template: `
        <div [ngClass]="{ 'placeholder': hidden }">
          <img [ngClass]="{ 'active': !hidden }" [src]="src" (load)="load()" (error)="error()" />
        </div>
      `
    })
    export class LazyImgComponent implements AfterContentInit {

      @Input() src: string;

      public img: HTMLImageElement;
      public hidden: boolean;

      constructor(public el: ElementRef) {
        this.hidden = true;
      };

      ngAfterContentInit() {

        var that  = this;

        that.img = that.el.nativeElement.querySelector('img');
        that.img.crossOrigin = 'Anonymous';

        // check if the images are already cached
        ImgCache.isCached(that.src, (path: string, success: boolean) => {

          if (success) {
            alert('cache ' + that.src);
            ImgCache.useCachedFile(that.img, function (){
                alert('now using local copy');
              }, function(){
                alert('could not load from cache');  // desnt work with live reload
              })

          } else {
            alert('no cache ' + that.src)
            ImgCache.useOnlineFile(that.img);
            ImgCache.cacheFile(that.src, () => { });


          }

        });
      }



      /**
       * This function will show the image when it has loaded
       */
      load(): void {
        this.hidden = false;
      }

      /**
       * This function will be triggered when http request fails
       */
      error(): void {
        this.img.remove();
      }

    }

2 个答案:

答案 0 :(得分:1)

您必须使用ionViewDidLoad()事件。

ionViewDidLoad()

  

页面加载后运行。此事件每页仅发生一次   被创造。如果页面离开但缓存,则此事件将   在随后的观看中不再发射。 ionViewDidLoad事件是   放置页面设置代码的好地方。

另一个事件是ionViewDidEnter()

ionViewDidEnter()

  

页面完全进入后运行,现在是活动页面。这个   无论是第一次加载还是缓存页面,都会触发事件。

这是official doc

答案 1 :(得分:0)

动态生成的内容是在初始化时创建的吗?或者它是否依赖于某些可观察的模式,在初始化完全发生之前,URL可能不会出现?

您可以尝试的另一个生命周期钩子是ngAfterContentInit()

  

在Angular将外部内容投射到组件之后做出响应   图。

     

在第一次ngDoCheck()之后调用一次。

     

仅限组件的挂钩。