Angular 2-子列表循环到选择html元素 [英] Angular 2 - Sublist loop to a select html element

查看:61
本文介绍了Angular 2-子列表循环到选择html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象数组.

I have an array of objects like this.

{
  id: 1,
  name: 'Name 1'
  children: [
     {
       id: 2,
       name: 'Name 2'
     }
  ]
},
{
  id: 3,
  name: 'Name 3'
  children: [
     {
       id: 4,
       name: 'Name 4'
     }
  ]
}

现在我需要将所有这些选项都设置为一个选择元素.

Now i need to make all of them options to a select element.

如果我做

<option *ngFor="let element of elements" value="{{element.id}}">― {{element.name}}</option>

它将仅显示名称1"和名称3".我应该如何使循环包含所有元素

It will show only "Name 1" and "Name 3". How should I make the loop to include all the elements

我不想使用包含4个项目的数组.我试图找到一种无需更改数组的方法

I don't want to use an array with 4 items. I'm trying to find a way without the need of change the array

名称1",名称2",名称3",名称4"

"Name 1", "Name 2", "Name3", "Name 4"

谢谢

推荐答案

1)您可以利用ngForTemplate获得所需的结果:

1) You can leverage ngForTemplate to achieve desired result:

<select>
  <ng-template ngFor [ngForOf]="elements" [ngForTemplate]="itemTemplate"></ng-template>
  <ng-template #itemTemplate let-element>
    <option value="{{element.id}}">― {{element.name}}</option>
    <ng-template ngFor [ngForOf]="element.children" [ngForTemplate]="itemTemplate"></ng-template>
  </ng-template>
</select>

它适用于任何级别的子元素

It should work for any level of sub elements

柱塞示例

Plunker Example

2)另一种方法可能是使用自定义管道,例如:

2) Another way might be using custom pipe like:

@Pipe({
  name: 'flatten'
})
export class FlattenPipe {
  transform(arr: any[], property: string) {
    if(!arr) return [];
    return arr.reduce((acc, cur) => {
      return [...acc, cur, ...this.transform(cur[property], property)];
    }, [])
  }
}

和html

<select>
  <option *ngFor="let element of elements | flatten: 'children'" value="{{element.id}}">― {{element.name}}</option>
</select>

它也应该适用于任何级别的子元素

It should also work for any level of sub elements

柱塞示例

Plunker Example

这篇关于Angular 2-子列表循环到选择html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆