0

I have an img tag in my HTML with src value supplied through property binding like this :

<img [src]="imgSrc" id="myimage">

imgSrc variable exists in the .ts file. Its value is a URL

When i try to access this URL in my .ts file using

document.getElementById('myimage').src

It is showing null. It works fine if I do not use property binding and supply the value directly in HTML template. When I console log document.getElementById('myimage'), the proper img tag with correct src is logged. I have tried using @ViewChild instead of ID as well but that is also not working. I know I can use imgSrc variable in my .ts file but how to access src property.

Urooj
  • 151
  • 7
  • *"It is showing null."* What does that mean? I think it's much more likely that it's throwing an error saying "Cannot read property 'src' of null."* which is not the same thing as "showing" it. – T.J. Crowder Jul 22 '22 at 12:42
  • 1
    `myImage` != `myimage`, ID values are case sensitive. So the issue above is covered by the linked previous question's answers. But separate from that, I strongly suspect that you shouldn't be looking up the element by ID using a DOM method like that in an Angular project. (I don't do Angular, but most MVC frameworks like it provide a more encapsulated way to access rendered elements.) – T.J. Crowder Jul 22 '22 at 12:44
  • I hope you found your answer in the related question. Please don’t forget to [provide a helpful `alt` text for your image](https://webaim.org/techniques/alttext/). – Andy Jul 22 '22 at 12:53
  • @T.J.Crowder what i meant is that document.getElementById('myimage') returns an img object ....there is no console error....but it's src property is null – Urooj Jul 22 '22 at 16:42
  • @Andy , the related question has a different issue. In my case the element is found but its src property is null – Urooj Jul 22 '22 at 16:44
  • 1
    @Urooj - The `src` of an `HTMLImageElement` is **never** `null`. ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/src) | [Spec](https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-src)) It can be `""` if there is no `src` attribute on the image at all, but not `null`. – T.J. Crowder Jul 22 '22 at 16:51
  • Could you share some more code please? Withouth at least parts of the .ts file it’s very hard to guess what your issue is. It’s very likely, though, that it’s in your javascript, not your HTML. – Andy Jul 23 '22 at 15:05

0 Answers0