如何在一个指令上使用多个ngFor进行属性绑定

时间:2018-12-03 17:53:15

标签: javascript arrays angular angular2-directives property-binding

我正在使用提供draggable指令的ng-drag和drop npm模块。我还有一个2D数组,其中包含要在li元素中显示的项目列表,并使每个元素都可拖动。事实是,我不能使用多个ngFor,因为这在角度上无效,因此我需要找到一种解决方法。为此,我将内部数组项包装在ng-container内,但这无济于事,因为这样我就不能拖动单个li项,因此它包装了整个列表。我想出的唯一主意是:

app.component.ts

  vegetables = [[
{name: 'Carrot', type: 'vegetable'},
{name: 'Onion', type: 'vegetable'},
{name: 'Potato', type: 'vegetable'},
{name: 'Capsicum', type: 'vegetable'}],
[
  {name: 'Carrotas', type: 'vegetable'},
  {name: 'Onionas', type: 'vegetable'},
  {name: 'Potatoas', type: 'vegetable'},
  {name: 'Capsicumas', type: 'vegetable'}]]

this.i++;

      this.indexes = this.vegetables[this.i];

app.component.html

<li class="list-group-item list-group-item-action list-group-item-success" [draggable] *ngFor="let item of [this.indexes]" [dragClass]="'active'" [dragTransitClass]="'active'" [dragData]="item" [dragScope]="item.type" [dragEnabled]="dragEnabled">
      {{item.name}}

</li>

但这也不打印任何内容。

现在我这样离开我的代码:

 <li class="list-group-item list-group-item-action list-group-item-success" [draggable] *ngFor="let item of [vegetables[0]]" [dragClass]="'active'" [dragTransitClass]="'active'" [dragData]="item" [dragScope]="item.type" [dragEnabled]="dragEnabled">
  <ng-container *ngFor="let items of item">
      {{items.name}}
  </ng-container>
</li>

但是它将所有数组外部索引中的所有项目放在一个li行中,并且没有按我的需要分隔可拖动项目,如下所示:

enter image description here

但是我希望每个项目都位于单独的绿色行中,并且每个字段都可以拖动。

1 个答案:

答案 0 :(得分:3)

您很近。您需要将ling-container进行反转,这样会很好。示例:

<ng-container *ngFor="let item of [vegetables[0]]">
  <li 
    *ngFor="let items of item"
    class="list-group-item list-group-item-action list-group-item-success"
    [draggable]
    [dragClass]="'active'"
    [dragTransitClass]="'active'"
    [dragData]="item"
    [dragScope]="item.type"
    [dragEnabled]="dragEnabled">
    {{items.name}}
  </li>
</ng-container>