使用ngFor循环更新角度2中的元素

问题描述 投票:0回答:2

我正在尝试了解新Angular中的一些功能。我以前只使用过AngularJS,因此我正在尝试自己使用新的TypeScript版本。如果我有一个遍历我的数据对象的模板,那么我该如何设置一个模型,以便在点击(或单击)某些内容时,它只会反映模板中该元素的更新。

我试图实现的是,如果单击reportImage,则只有带有p.id的元素将更新信息。

这是我目前尝试的全部尝试,但我认为我没有正确使用ngModel。

模板:

<div class="card" *ngFor="let p of posts" [(ngModel)]="post[p.id]">
<img [src]="p.img" (tap)="reportImage($event, p.id)">
<button>
  <i [name]="icon.name" class="fa {{ icon.class }}"></i>
</button>
</div>

TypeScript:

 public tap: number = 0;

 buttonClass(id: number) {

    if(this.post[id].icon.name === 'heart-o') {
      this.post[id].icon.class = 'heart';
    }
    else {
      this.post[id].icon.name = 'heart-o';
      this.post[id].icon.class = 'heart-o';
    }
  }

  reportImage(times, id: number) {
    this.tap++;
    if(this.tap % 2 === 0) {
      this.buttonClass(id);
    }
  }

任何其他可以学习的方向或教程都很好。

angular typescript
2个回答
0
投票

尝试这个。

HTML:

<div *ngFor="let p of posts">
<img [src]="p.img" (click)="reportImage($event, p)">
<button>
  <i [name]="p.icon.name" class="fa {{ p.icon.class }}"></i>
</button>
</div>

TS:

reportImage(times, currentOne) {
    this.tap++;
    if(this.tap % 2 === 0) {
      this.buttonClass(currentOne);
    }
  }

buttonClass(currentOne) {

    if(currentOne.icon.name === 'heart-o') {
      currentOne.icon.class = 'heart';
    }
    else {
      currentOne.icon.name = 'heart-o';
      currentOne.icon.class = 'heart-o';
    }
  }

*您的代码中有很多错误。1. Icon-指什么?它是一个全局变量2. (tap)-这是您的自定义事件,如果不使用,请使用click而不是tap


0
投票

我对您的问题的理解是,当您单击图像时,您想更改该图像所属的特定对象中的数据。只需检查一下我用stackblitz编写的这段代码,它与您的代码非常相似。https://stackblitz.com/edit/angular-7qfv7v

© www.soinside.com 2019 - 2024. All rights reserved.