【问题标题】:How to show a specific object in object array (Angular 5, TypeScript)如何在对象数组中显示特定对象(Angular 5,TypeScript)
【发布时间】:2018-09-24 05:04:21
【问题描述】:

我在 Angular 5 中有一个数据提供者。

export class DataProvider {
  location: any;

  private locations: any[] = [
    {
      "name": "restaurant",
      "location": "downtown",
      "category": "restaurant",
      "id": "1"
    },

    {
      "name": "law firm",
      "location": "center city",
      "category": "office",
      "id": "2"
    },

    {
      "name": "public library",
      "location": "suburb",
      "category": "library",
      "id": "3"
    } ]

这是我的 HTML 文件。

<div *ngFor="let location of locations">
   <h1></h1>
    <h2></h2>
</div>

在这种情况下,如何在具有某些属性的数据数组中加载特定对象(项)? 例如,如果我想用"category" :"restaurant" 加载一个对象,我应该如何处理我的 HTML 文件?所以另外两个不应该出现。我只想通过使用这个特定的属性来加载三分之一。

谢谢。

【问题讨论】:

    标签: javascript html arrays angular typescript


    【解决方案1】:

    您需要访问该属性。您可以使用以下示例

    <div *ngFor="let location of locations">
       <h1>{{location.name}}</h1>
        <h2>{{location.category}}</h2>
    </div>
    

    编辑

    根据类别进行过滤:

    locationsFiltered = this.locations.filter(location =>location.category=="restaurant");
    

    现在为了让这个例子更实用,我将创建一个方法来实现它

    filter(category : string) : any[] {
       return this.locations.filter(location =>location.category==category);
    }
    

    然后在html中

    <div *ngFor="let location of locationsFiltered">
       <h1>{{location.name}}</h1>
        <h2>{{location.category}}</h2>
    </div>
    

    【讨论】:

    • 感谢您的回复。是的,我知道该怎么做。但我的问题是,如果我只想加载一个带有 "category":"restaurant" 的对象,我该怎么办?另外两个不应该出现。
    • 我希望能够加载三分之一的......通过调用该对象的特定属性。我怎样才能做到这一点?谢谢,我将等待您的编辑。
    • 感谢您的编辑!我真的很感谢你的帮助。我现在就试试这个。
    • 我刚刚给了你工具。我会让他们使用它们。我建议使用选择列表w3schools.com/bootstrap/…
    • 对于最终的 html,你不需要在标题标签之间使用 {{location.name}} 和 {{location.category}}(就像在你的第一个 html sn-p 中一样)吗? (如果是这样,只需编辑,我将删除我的评论。)
    猜你喜欢
    • 2019-02-27
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2021-05-05
    • 2019-01-11
    • 2022-07-07
    • 2019-12-02
    相关资源
    最近更新 更多