从Ionic 3.5

时间:2017-10-30 16:40:48

标签: angular typescript ionic-framework ionic3

我正在尝试在Ionic 3.5中完成一个简单的任务,我想在页面加载后加载一个函数来显示图像“ad”。

目前我点击它时会设置按钮,它会正确加载此图像。我只是想在页面加载时自动发生此功能。

我试图在页面加载上运行该函数,就像这样......

import { Component, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ImageViewerController } from 'ionic-img-viewer';


@IonicPage({
  segment: 'sponsor/:sponsorId'
})
@Component({
  selector: 'page-sponsor-detail',
  templateUrl: 'sponsor-detail.html',
})

export class SponsorDetailPage {

  // @ViewChild('#myImage') myImage: ElementRef;

  sponsor: any;
  _imageViewerCtrl: ImageViewerController;

  constructor(public navCtrl: NavController, public navParams: NavParams, imageViewerCtrl: ImageViewerController, private element: ElementRef) {
    this._imageViewerCtrl = imageViewerCtrl;
  }

  ionViewWillEnter() {
      var imgObj = this.element.nativeElement.querySelector('#myImage');
      console.log(this.element);
      console.log(imgObj);
      // this.presentImage(imgObj);
  }

  presentImage(myImage: any) {
      const imageViewer = this._imageViewerCtrl.create(myImage);
      imageViewer.present();
  }

赞助商详情视图

//sponsor-detail.html
<button *ngIf="sponsor?.ad" ion-button round (click)="presentImage(myImage)"><ion-icon name="eye"></ion-icon>&nbsp;Visit Ad</button>
<img id="myImage" style="display:none;" [src]="sponsor?.ad" #myImage (click)="presentImage(myImage)" />

然而,我似乎无法从querySelector返回任何数据,尽管“this.element”包含我试图定位的视图上的所有数据。我试图将事件定位为“img”标记,但这也不会返回任何内容。我读了一些关于ViewChild的事情,但是自己无法使用它实现任何东西。

也许另一种解决方案是在页面完成渲染时触发视图中的click事件,但我想确保解决方案能够跨平台工作。

我是Ionic和Angular的新手,感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

您可以使用ionViewDidLoad方法:

@Page({
  templateUrl: 'build/pages/somepage/somepage.html'
})
export class SomePage {
  constructor() {
    // ...
  }

  ionViewDidLoad() {
    // Put here the code you want to execute after the page has fully loaded
  }
}

此外,现在采用更好的方法是使用局部变量而不是搜索DOM。你可以给出一些像这样的局部变量:< / p>

<img id="myImage" style="display:none;" [src]="sponsor?.ad" #myImage (click)="presentImage(myImage)" />

然后使用@ViewChild抓住它:

import {ElementRef, ViewChild} from '@angular/core';
@ViewChild('myImage') myImage: ElementRef;

ionViewDidLoad() {
    // do what you want with this.myImage
}