简体   繁体   English

HTML 错误:“类型上不存在属性”即使未显示

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

I have a HTML file using AngularJS that looks like this:我有一个使用 AngularJS 的 HTML 文件,如下所示:

<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.我试图做到这一点,因此如果项目是该类别,应用程序只读取存在于特定类别的属性,但无论事先使用 ngIf 语句如何,程序似乎仍会读取它们并抛出“类型上不存在属性”即使从未显示这些属性也会出错。

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:我对解决这个问题的最佳猜测是在调用特定属性以处理它们丢失时实现一个“if”语句,如下所示:

 <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.我不知道如何使用 HTML 或 AngularJS 来做到这一点,或者这是否是一个可行的解决方案。 How would I solve this problem?我将如何解决这个问题?

It looks like the category property on Item isn't always present.看起来Item上的category属性并不总是存在。

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)使用条件链接来处理边缘情况,如果属性丢失,则条件失败为 false(您需要预处理 JS 才能使其工作)
  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在该代码之前放入某种 null 检查以确保属性始终存在并将其设置为空字符串或false或其他东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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