简体   繁体   English

Angular 7-如何在HTML对象中显示数组

[英]Angular 7 - How to display array inside of an object in HTML

I am trying to display array inside of an object in HTML. 我正在尝试在HTML对象中显示数组。 My sample JSON is like below... 我的示例JSON如下所示...

I would like to display Product > ProductCategoryRelations > Category.Name in a string comma separeted like "Category 1, Category 2" 我想以逗号分隔的字符串形式显示“产品”>“ ProductCategoryRelations”>“ Category.Name”,例如“ Category 1,Category 2”

[
  {
    "Id": 2,
    "Name": "Product 1",
    "ProductCategoryRelations": [
        {
                "Id": 3,
                "ProductId": 2,
                "CategoryId": 2,
                "Active": true,
                "Category": {
                        "Id": 2,
                        "ParentId": 1,
                        "Name": "Category 1"                    
                }
        },
        {
                "Id": 4,
                "ProductId": 2,
                "CategoryId": 2,
                "Active": true,
                "Category": {
                        "Id": 2,
                        "ParentId": 1,
                        "Name": "Category 2"
                }
        }
    ],

How can I put all categories name in a string comma seperated? 如何将所有类别名称放在逗号分隔的字符串中?

What I have so fas is like below but it doesnt worrk 我有这样的fas如下所示,但它并不担心

<dd class="col-sm-9" *ngFor="let category of product.ProductCategoryRelations">
  <span>{{category.Name}}</span>
</dd>

In javascript, you would need this: 在javascript中,您需要以下代码:

product.ProductCategoryRelations
        .map(r => r.Category.Name)
        .join(',')

to put it in context: 放在上下文中:

 let product = { "Id": 2, "Name": "Product 1", "ProductCategoryRelations": [ { "Id": 3, "ProductId": 2, "CategoryId": 2, "Active": true, "Category": { "Id": 2, "ParentId": 1, "Name": "Category 1" } }, { "Id": 4, "ProductId": 2, "CategoryId": 2, "Active": true, "Category": { "Id": 2, "ParentId": 1, "Name": "Category 2" } } ], }; console.log( product.ProductCategoryRelations .map(r => r.Category.Name) .join(',') ); 

Now you can use .join(',') in Angular template syntax, but you cannot use the .map() bit. 现在,您可以在Angular模板语法中使用.join(',') ,但不能使用.map()位。 So I suspect the easiest way would be to add a utility function to your component that does this for you: 因此,我怀疑最简单的方法是在您的组件中添加一个实用程序功能来为您执行此操作:

getCategoryNames(product) {
  return product.ProductCategoryRelations.map(r => r.Category.Name);
}

and then do it in the template like this: 然后在模板中执行以下操作:

{{getCategoryNames(product).join(',')}}

If you need to do the same thing in multiple places in your app across multiple components, then I would recommend writing your own custom pipe . 如果您需要跨多个组件在应用程序中的多个位置执行相同的操作,那么建议您编写自己的自定义管道

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

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