【问题标题】:Get element from view, inside controller in Ionic 3.5从视图中获取元素,在 Ionic 3.5 中的控制器内部
【发布时间】:2017-10-30 16:40:48
【问题描述】:

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

目前我有一个按钮设置,当您单击它时,它将正确加载此图像。我只是希望这个功能也能在页面加载时自动发生。

我试图像这样在页面加载时运行该功能......

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)" />

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

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

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

【问题讨论】:

  • 您需要在此处提供更多code。包括constructor 和更多html 内容。
  • @Sampath 我现在添加了更多代码

标签: angular typescript ionic-framework ionic3


【解决方案1】:

您可以使用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。你可以像这样给一些局部变量:

<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
}

【讨论】:

  • 当我尝试您发布的 ViewChild 解决方案时,当 console.log this.myImage 的结果时我得到未定义
  • 如我所见,您的 标签有一个 display:none 内联样式。您确定页面加载时它存在于 DOM 中吗?
  • 嗨保罗,多一点挖掘..这似乎有效..但我不知道为什么它在 ionViewDidLoad 函数中是必要的..setTimeout(() => { this .presentImage(this.myImage.nativeElement); },350);如果没有 setTimeout,this.myImage 属性是未定义的
猜你喜欢
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多