0

When parsing rss feed in xml format, I display the images that are contained in the attibute url inside the tag <enclosure> but whenever the tag enclosure is missing because the article does not have an image, I'm getting an error in the console saying:

Cannot read property 'getAttribute' of undefined

I tried to solve this problem using onError function inside src but when the tag is missing I'm still getting the error in the console and the placeholder image is not shown.

Here's my html file:

<ion-header>
  <ion-navbar color="primary">
    <ion-title text-center>
      App Name
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-item *ngFor="let entry of entries" (click)="openPage(entry)" text-wrap>
      <ion-thumbnail>
        <img class="imgmg" src="{{entry.getElementsByTagName('enclosure')[0].getAttribute('url')}}" onError="this.src='assets/images/placeholder_image.png';" >
      </ion-thumbnail>
      <h2 class="title">{{entry.getElementsByTagName('title')[0].textContent}}</h2>
    </ion-item>
  </ion-list>
</ion-content>
Pier
  • 794
  • 1
  • 12
  • 27

1 Answers1

2

You can use *ngif. example:

<img *ngIf="entry.getElementsByTagName('enclosure')[0].getAttribute('url')" class="imgmg" src="{{entry.getElementsByTagName('enclosure')[0].getAttribute('url')}}">
<img *ngIf="!entry.getElementsByTagName('enclosure')[0].getAttribute('url')" class="imgmg" src="assets/images/placeholder_image.png">

also check this link

EDIT:

<img *ngIf="image_available" class="imgmg" src="{{entry.getElementsByTagName('enclosure')[0].getAttribute('url')}}">
<img *ngIf="!image_available" class="imgmg" src="assets/images/placeholder_image.png">
amin arghavani
  • 1,883
  • 14
  • 21
  • I added them both inside `` but I'm getting this error: `Unhandled Promise rejection: Template parse errors: Can't bind to 'ngif' since it isn't a known property of 'img'.` – Pier Jan 20 '17 at 12:57
  • Check till where you got something and change ngif. I update the answer. please use the approach. – amin arghavani Jan 20 '17 at 13:56
  • This error has nothing to do with @aminarghavani 's solution. You have to import the correct module (BrowserModule or CommonModule): http://stackoverflow.com/questions/39058075/cant-bind-to-ngif-since-it-isnt-a-known-property-of-div – yadejo Jan 20 '17 at 14:01
  • @aminarghavani @yadejo It seems that the first answer you gave me was correct! I just had to make one little modification, `*ngIf` instead of `*ngif`. Thanks a lot :) – Pier Jan 20 '17 at 14:25
  • "[src]=" is better used when dealing with dynamic/expression image sources – Muhammad Omar ElShourbagy Dec 31 '17 at 09:37