简体   繁体   中英

HTML Error: "Property does not exist on type" even when not displayed

I have a HTML file using AngularJS that looks like this:

<div *ngIf="Item">
    <!-- Create a 'display' for each category. -->
    <div *ngIf='Item.category === "book"'>
        <p>Book Title: {{Item.booktitle}}</p>  
    </div>
    <div *ngIf='Item.category === "sport"'>
        <p>Sport: {{Item.sport}}</p>
    </div>
</div>

The file is supposed to check what category an item is, and display properties that are relevant to that category only. These categories are for different 'item' objects, and these items do not share these properties. I have tried to make it so the application only reads properties that exist for a specific category if the item is that category, but the program appears to still read them regardless of the ngIf statement beforehand and throws a "Property does not exist on type" error even though those properties are never displayed.

My best guess on solving this is to implement an 'if' statement in the calls for specific properties to handle them being missing, like so:

 <p>Book Title: {{ if Item.category ==="book" -> Item.booktitle, else -> "N/A" }}</p>

I do not know how to do so using HTML or AngularJS, or if this is even a viable solution. How would I solve this problem?

It looks like the category property on Item isn't always present.

To address this, you have a couple of options:

  1. Use conditional chaining to handle that edge case and fail the conditional as false if the property is missing(you'll need to pre-process the JS for that to work)
  2. Put some kind of null check in before that code to make sure the property is always there and set it to empty string or false or something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM