ERROR Error: Uncaught (in Promise): Typeerror: Cannot read Property 'src' of null

Asked

Viewed 757 times

-2

I want to take the "src" of an html image but keeps showing this error. I’m trying to do it this way

import { NavController, NavParams } from 'ionic-angular';
import { Component } from '@angular/core';

@Component({
  selector: 'page-sombraFase1',
  templateUrl: 'sombraFase1.html',
})
export class SombraFase1Page {
  src: any;
  constructor(public navCtrl: NavController, public navParams: NavParams) {
    var srcuu:any = (<HTMLImageElement>document.getElementById("sol")).src;
  }
  ionViewDidEnter(){
    console.log(this.src);
    
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ion-header>
</ion-header>

<ion-content class="bgcSombra" padding>
  <img src="assets/img/cabecalho.png" alt="Cabeçalho" id="cabecalho" (click)="voltarHome()">
  <div class="divDica">
    <img src="assets/img/audio.png" class="dica">
    <img src="assets/img/msgDica.png" class="msgDica">
  </div>
  <div class="imgsGame">
    <img src="assets/img/Sol.png" id="sol">
    <img src="assets/img/lua.png" id="lua">
    <img src="assets/img/Sol-sombra.png" id="solSombra">
    <img src="assets/img/lua-sombra.png" id="luaSombra">
  </div>
</ion-content>

It keeps returning null, how can I solve this problem ?

  • the error occurs on the line var srcuu:any = (<HTMLImageElement>document.getElementById("sol")).src;?

  • Does not occur in the constructor line

  • I even made an answer, but I was in doubt when I changed the line to var srcuu:any = (<HTMLImageElement>document.getElementById("sol").src);. I don’t know if this is right, but it seemed valid... or not?

1 answer

0

As you are trying to access an element based on your id, you could use the Decorator angular ViewChild instead of using pure Javascript.

sombraFase1.html

<ion-content class="bgcSombra" padding>

  ...

  <div class="imgsGame">
    <img #minhaImagem src="assets/img/Sol.png" id="sol">

    ...

  </div>
</ion-content>

sombraFase1.ts

import { Component, ViewChild } from '@angular/core';

...

export class SombraFase1Page {
  @ViewChild('minhaImagem') minhaImagem;

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    console.log(this.minhaImagem); //visite seu elemento usando this.minhaImagem
  }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.