【问题标题】:Class Binding when applying it to a *ngFor for an element将其应用于元素的 *ngFor 时的类绑定
【发布时间】:2023-04-04 06:32:01
【问题描述】:

我需要一些帮助,但由于某种原因我想不出如何解决它

我有一个对象数组,我用 *ngFor 和

循环这些对象
  • 我想将类绑定添加到我的数组中的字段(描述详细信息),但我不希望该操作发生在每个“详细描述”上

  • 就是我正在使用的那个。不确定这是否可能。希望我说得通。

    目前,当我展开“详细说明”时,每个具有“详细说明”的对象也会展开(不希望发生这种情况)!

    --------HTML------------

    <div *ngFor="let n of Entry">
            <ul class="list-group">
             <li>
              <p class="description"> Detailed Description
               <span class="glyphicon" [class.glyphicon-minus- 
               sign]="expandedDetails" [class.glyphicon-plus- 
               sign]="!expandedDetails" (click)="toggleDetails()"></span>
                </p>
                <span class="entryDetails" *ngIf="expandedDetails == true"> 
                 {{n.description}}</span>
    

    ---------TS----------

    toggleDetails() {
    this.expandedDetails = !this.expandedDetails;
    

    }

  • 【问题讨论】:

    • 您应该将expandedDetails 标志添加到Entry 类并仅为您单击的项目切换标志:(click)="n.expandedDetails = !n.expandedDetails"。显示细节的条件是:*ngIf="n.expandedDetails".

    标签: angular typescript ngfor


    【解决方案1】:

    试试这个

    在 ts 文件中定义切换变量

     toggle=[]
    

    在你的 html 中像这样修改你的代码

    <div *ngFor="let n of Entry;let i =index">
            <ul class="list-group">
             <li>
              <p class="description"> Detailed Description
               <span class="glyphicon" [class.glyphicon-minus- 
               sign]="expandedDetails" [class.glyphicon-plus- 
               sign]="!expandedDetails" (click)="toggle[i]=toggle[i]  "></span>
                </p>
                <span class="entryDetails" *ngIf=" toggle[i]"> 
                 {{n.description}}</span>
    

    【讨论】:

    • (click)="toggle[i]=!toggle[i]
    • 是使用索引来查找元素
    【解决方案2】:

    您想在 for-each 上使用 trackby $index,然后您可以使用此值传递给 toggleDetails。因此,您只会打开该行/项目的详细信息。

    举个例子

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2018-04-12
      • 2018-05-29
      • 2015-01-16
      • 2020-09-15
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      相关资源
      最近更新 更多