【问题标题】:How to get index value in ng-template for primeng dropdown如何在 ng-template 中为primeng下拉列表获取索引值
【发布时间】:2020-11-25 20:38:00
【问题描述】:

我试图在 ng-template 中为primeng下拉列表获取索引值,但它给了我空值。这是示例代码

<p-dropdown [options]="cards" [(ngModel)]="selectedCard">
 <ng-template let-card let-i="index" pTemplate="item">
  <span>{{i}}</span>
 </ng-template>
</p-dropdown>

【问题讨论】:

    标签: html angular primeng


    【解决方案1】:

    如果你检查primengsource代码你会发现通过了传递选项的项目所以没有关于索引的信息

     <ng-container *ngTemplateOutlet="template; context: {$implicit: option}"></ng-container>
    

    一种方法是创建一个管道来查找传递的选项的索引基数

    @Pipe({
      name: 'indexOf'
    })
    export class IndexOfPipe implements PipeTransform {
    
      transform(items:any[] , item:any): any {
        return items.indexOf(item);
      }
    
    }
    

    例子

    <p-dropdown [options]="cities" [(ngModel)]="selectedCountry" 
         optionLabel="name" [filter]="true" [showClear]="true"
        placeholder="Select a Country">
    
        <ng-template let-item pTemplate="item">
    
            <div>?{{item.value.name}} {{cities | indexOf:item.value}} </div>
    
        </ng-template>
    </p-dropdown>
    

    demo ??

    【讨论】:

      【解决方案2】:

      你可以试试&lt;span&gt;{{cards.indexOf(card)}}&lt;/span&gt;

      我认为 ng-template 中的let-i="index" 在primeng 9.x 文档中没有提及。

      【讨论】:

      • ? 您使用传递选项的 indexOf 方法是对的,但您需要使用管道,否则 card.indexOf(card) 将在每次更改检测中运行,并且可能会影响纯性能跨度>
      • @malbarmavi 如果我错了,请纠正我。我认为在渲染组件后,如果他从数组中间移除一张卡片,那么管道将不会检测到 cards 的更改。所以解决方案不支持双向绑定吧?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多