【问题标题】:Access different object within a ngFor访问 ngFor 中的不同对象
【发布时间】:2019-09-25 11:36:15
【问题描述】:

我有一个 mat-grid-list,它遍历我创建的一些拍卖,以制作不同的 mat-grid-tiles。 在我的拍卖中,我有 CarId 和 BidId。 在我的 ngFor="让拍卖拍卖" 中,我想访问这些 Id 并使用它们来显示 CarType 和来自 Car 和 Bid 对象的出价金额。

在下面的代码中我想把“0”换掉:

{{allCars[0].CarType}} {{bids[0].Amount}}

切换它,以便我可以访问和使用 {{auctions.CarId}} 和 {{auctions.BidId}} 将正确的汽车类型和出价金额连接到 mat-grid-tile。 您对如何实现这一目标有任何想法吗?

    <div class="col-md-8 col-sm-12">
      <mat-grid-list cols={{breakpoint}} rowHeight="150px" gutterSize="1" (window:resize)="onResize($event)">
        <mat-grid-tile *ngFor="let auction of auctions"
                       [colspan]="1"
                       [rowspan]="1"
                       [style.border]="'1px double black'"
                       [style.background]="lightblue">


          <div class="text-inside-grid">
            Bil type:
            {{allCars[0].CarType}}
            <br />
            Start dato:
            {{auction.StartDate.toLocaleTimeString()}}
            {{auction.StartDate.toLocaleDateString()}}
            <br />
        Slutt dato:
        {{auction.StartDate.toLocaleTimeString()}}
        {{auction.EndDate.toLocaleDateString()}}
        <br />
        Nåværende bud:
        {{bids[0].Amount}}
        <li><a href="auction/{{auction.Id}}">Se auksjon</a></li>
      </div>
    </mat-grid-tile>
  </mat-grid-list>
</div>

数据结构:

interface Car {
  Id: number;
  CarType: string;
  flag: string;
  LicensePlate: string;
  KilometersDriven: number;
  Equipment: Array<Equipment>;
  FuelTypeId: number;
  Seats: number;
  GearTypeId: number;
  CityId: number;
  ColourId: number;
  Gears: number;
}

interface Auction {
  Id: number;
  Active: boolean;
  StartDate: Date;
  EndDate: Date;
  CarId: number;
}

interface Bid {
  AuctionId: number;
  Amount: number;
}

【问题讨论】:

  • 你不能只做{{allCars[auction.CarId].CarType}}{{bids[auction.BidId].Amount}}吗?
  • 很遗憾这不起作用。
  • 可以发一下allCarsbids的数据结构吗?没有组件代码很难解决。
  • 也用数据结构编辑了问题。

标签: html angular-material


【解决方案1】:

您可以在组件中实现两个函数,通过其 ID 从数组中检索对象/对象属性。

组件:

public getCarType(carId: number): string {
  return this.allCars.find(car => car.Id === carId).CarType;
}

public getBid(auctionId: number): number {
  return this.bids.find(bid => bid.AuctionId === auctionId).Amount;
}

然后使用模板中的函数:

Bil type: {{getCarType(auction.CarId)}}

Nåværende bud: {{getBid(auction.Id)}}

【讨论】:

  • 非常感谢
猜你喜欢
  • 2020-10-23
  • 2016-06-02
相关资源
最近更新 更多