javascript - 如何在一个指令上使用多个 ngFor 进行属性绑定(bind)

标签 javascript arrays angular angular2-directives property-binding

我正在使用 ng-drag and drop npm 模块,它提供了 draggable 指令。我还有一个 2D 数组,其中包含我想要在 li 元素内显示的项目列表,并使每个项目都可拖动。问题是我不能使用多个 ngFor,因为这在 Angular 中无效,所以我需要找到一种方法来解决这个问题。为此,我将内部数组项包装在 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>

但它将外部数组索引中的所有项目放在一里行中,而不是根据我的需要分隔可拖动项目,如下所示:

enter image description here

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

最佳答案

你很接近。您需要反转 li 和 ng-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>

关于javascript - 如何在一个指令上使用多个 ngFor 进行属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53599200/

相关文章:

javascript - 替换html字符串中的标签

javascript - 将 iframe 内容传输到新的空 iframe

java - 类数组,特定类的子类

angular - 使用 ng2-semantic-ui 在 select 中加载远程选项不起作用

asp.net - 如何使用 Angular 2/4 开发搜索建议文本框

javascript - 如果所有模型值不为空则显示 Angular

javascript - 无法读取 ARRAY Javascript 中未定义的属性 '0'

Java:命令行输入的总和给出数组*答案的长度

用于向量化函数的 Python 和 Numba

angular - 使用 DomSanitizer 后,图片网址仍然不安全