Accessing element from view within controller in Ionic version 3.5

I am currently working on a project in Ionic 3.5, where I need to implement a feature that automatically loads an image "ad" after the page finishes loading.

Right now, clicking a button successfully displays the image. However, I want this functionality to occur automatically when the page is loaded without needing user interaction.

I attempted to execute the function on page load like this...

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 View

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

However, I am not able to retrieve any data using querySelector despite having all the necessary data in "this.element". Even targeting just an "img" tag does not yield any results. I have looked into ViewChild but struggled to implement it effectively.

One potential solution might be triggering the click event in the view once the page has finished rendering, ensuring it works across different platforms.

As a newcomer to Ionic and Angular, any guidance would be greatly appreciated!

Answer №1

If you want to execute code after a page has fully loaded, you can utilize the ionViewDidLoad method:

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

  ionViewDidLoad() {
    // Add your desired code here to run after the page is completely loaded
  }
}

An alternative approach that is considered more efficient is using a local variable instead of searching through the DOM. You can assign a local variable like this:

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

Subsequently, access it using @ViewChild:

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

ionViewDidLoad() {
    // Implement actions involving this.myImage
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

$cordovaSQLite.execute does not exist as a method

I am inexperienced with ionic 1 and I am trying to input data into my sqlite table using a form. However, upon clicking the submit button, an error is displayed below: TypeError: $cordovaSQLite.execute is not a function at ChildScope.$scope.insertNewI ...

Tips for retrieving a JSON object value using a key in Angular 6 View

As a beginner in Angular 6, I am struggling to figure out how to access values from a JSON object in the view using keys. In my service, I am making an http.get(url) call and then invoking that method in my component. export class CustomersComponent impl ...

Guide to creating a Unit Test for an Angular Component with a TemplateRef as an Input

Looking to create unit tests for an Angular component that can toggle the visibility of contents passed as input. These inputs are expected to be defined as TemplateRef. my-component.component.ts @Component({ selector: "my-component", templateUrl ...

What are the benefits of incorporating NgRx in Angular, even when data is consistently synchronized through two-way data binding?

NgRx, analogous to Redux in React, is a tool used for state management in Angular. While state management can become convoluted in React projects, Angular typically avoids this issue thanks to its two-way data binding synchronization. Interestingly, many ...

Angular strictPropertyInitialization - best practices for initializing class members?

When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data. I have considered 3 options. But which one is the most appropriate? Is there another alt ...

Accessing Github REST API with Next-auth token

Looking to enable user login and retrieve specific user data using the Github REST API, such as repositories and issues. After successfully implementing the login feature, I encountered an obstacle with the Github REST API that requires a token for endpoi ...

Unable to extract the 'data' property from an undefined source in React, causing an error

I encountered this error message: TypeError: Cannot destructure property 'data' of '(intermediate value)' as it is undefined. export const getServerSideProps: GetServerSideProps = async () => { // categories const { data: categor ...

Controlling the visibility of components or elements in Angular through input modifications

Is there a more efficient way to handle button disabling and enabling based on email validation in Angular? I already have form controls set up, but want to make the process cleaner. The goal is to disable the "Get Started" button by default if the email a ...

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...

I'm having trouble getting angular/material to function properly

I've used the following command to install: npm install --save @angular/material @angular/cdk Afterwards, I made additions to app.module.ts import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatButto ...

How can I prevent an element from gaining focus after opening a NgbModal?

In the template, I am using a ngForm which is passed as an argument to open a NgbModal: <form #optionsForm="ngForm" noValidate (ngSubmit)="saveOptions()" id="optionsForm"> <div class="modal-body"> <div class="form-group"> < ...

Set theme value for the tab group in Angular Material

Trying to change the tab theme in Angular Material by setting it directly seems to be a bit tricky. The example from Angular Material shows how to do it with a toggle button, but when I try to code it directly, it doesn't work. Here's the code sn ...

Component's mocking service is being ignored

I am currently exploring how to simulate a service (specifically one that makes http calls) in order to test a component. @Component({ selector: 'ub-funding-plan', templateUrl: './funding-plan.component.html', styleUrls: ['. ...

Unraveling the complexities of Typescript's Advanced Type NonFunctionPropertyNames

Delving deeper into the realm of advanced types in Typescript, I came across an intriguing type called NonFunctionPropertyNames. This type is designed to extract only the properties of a given object that are not functions. type NonFunctionPropertyNames&l ...

Troubles with Angular 2 directive interactions: input vs. output discrepancies

I'm having trouble binding variables for inputs and outputs. I'm not sure what I'm doing incorrectly. HTML <p [timeDelta]="'2016-09-20 00:00:00'">{{delta}}</p> Below is the code for my directive: import { Directive, ...

Displaying a segment of information extracted from a JSON array

I'm currently tackling a project that involves using React, Redux, and TypeScript. Within the JSON file, there is a key-value pair: "data_start": "2022-09-02" Is there a way to display this date in a different format, specifical ...

Modifying the State in a Class Component

private readonly maxSizeOfDownloadedFiles: number = 1000000; state = { totalSum: this.maxSizeOfDownloadedFiles }; handleCallback = () => { this.setState({ totalSum: 12 }) alert('totalSum ' + this.state.totalSum); }; Upon executing the ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Creating a data structure that filters out specific classes when returning an object

Consider the following scenario: class MyClass {} class MyOtherClass { something!: number; } type HasClasses = { foo: MyClass; bar: string; doo: MyClass; coo: {x: string;}; boo: MyOtherClass; }; type RemovedClasses = RemoveClassTypes& ...

The Facebook provider is missing in Ionic Native

An error has occurred: No provider for Facebook!     InjectionError (core.es5.js:1231)     NoProviderError (core.es5.js:1269)     ReflectiveInjector_ ...