【问题标题】:Add class to element inside *ngFor将类添加到 *ngFor 内的元素
【发布时间】:2019-05-08 17:30:15
【问题描述】:

我有一个使用*ngFor 生成的项目列表:

<div *ngFor="let item of items"> 
  <div>
     <span>item.description<span>
     <span>item.price</span>
     <button (click)="removeItem(item.id)"> x <button>
  </div>
  ...

removeItem 函数向 API 端点发出 DELETE 请求并成功删除该项目,但除非我刷新页面,否则该项目仍保留在视图中。

我想要的是应用一个类来设置display:none到被删除的项目,我用过这个:

<div *ngFor="let item of items" [class.dismissed]="itemRemoved">

.ts 文件中,itemRemoved 是这样初始化的:

itemRemoved: boolean = false;

并且在函数中removeItem在API调用成功时设置为true

this.http.delete(url)
  .subscribe(
    response => {
      console.log("Item removed");
      this.itemRemoved = true;
    },

但该类适用于所有项目。

如何将类仅应用于我要移除的项目?

感谢您的帮助!

【问题讨论】:

  • 如果该项目从items 数组中删除,它将从 DOM 中删除。应该没有必要使用display: none
  • 如@user184994 所述,您可以修改removeItem 方法以使用传递的id 搜索item,然后从@ 中删除它(使用splice 或任何其他方法) 987654338@数组
  • @roymckrank 你能显示你的组件代码以便我可以帮助你

标签: angular ngfor iterable


【解决方案1】:

只需将isRemoved 属性分配给您的item,这样我们就可以区分哪个项目被删除了。因此,您需要将整个项目传递给方法函数,然后将isRemoved 属性分配给item。然后,如果删除了item,则使用 if 语句检测。

HTML

<div *ngFor="let item of items">
  <div *ngIf="!item.isRemoved">
     <span>item.description</span>
     <span>item.price</span>
     <button (click)="removeItem(item)"> x </button>
  </div>
</div>

然后在你的 TypeScript 中

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  items = [
    {
      description: 'sample',
      price: 10
    }
  ];

  public removeItem(item) {
    item.isRemoved = true;
  }
}

【讨论】:

    【解决方案2】:

    itemRemoved 是一个类范围的变量。当您将其设置为 true 时,它​​对每个人都是 true。一种方法是拥有一个已删除的 id 数组,并将一个函数传递给类输入,以检查该 ID 是否在所述数组中。

    (未经测试,但要点):

    export class MyComponent {
      removedItems: any[] = [];
    
      removeItem(item) {
        this.http.delete(url)
          .subscribe(response => {
            console.log("Item removed");
            this.removedItems.push(item);
          })
      }
    
      isRemoved(item) {
        return this.removedItems.find(i => item.id === i.id);
      }
    }
    

    模板:

    <div *ngFor="let item of items" (click)="removeItem(item)" [class.dismissed]="isRemoved(item)">x</div>
    

    编辑:

    或者正如 Juan 在 cmets 中提到的,从您正在迭代的数组中删除该项目。取决于items 的填充方式。

    【讨论】:

    • items 是一个对象,我会试试你的解决方案!
    【解决方案3】:

    您不需要一个类来从视图中删除该项目。最简单的方法是从您正在迭代的数组中删除该项目。在您的示例中:

      removeItem(item) {
        this.http.delete(url)
          .subscribe(response => {
            console.log("Item removed");
            let index = this.items.indexOf(item);
            this.items.splice(index,1);
          })
      }
    

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      • 2018-11-23
      • 2016-08-09
      • 2013-01-23
      • 2017-09-15
      • 1970-01-01
      • 2019-10-01
      相关资源
      最近更新 更多