Home > Mobile >  How to call a function with data from foreach method in HTML string?
How to call a function with data from foreach method in HTML string?

Time:05-05

I am generating some html card and buttons from an array. I want to call a function with the data from the foreach. But I can't seem to figure it out.

I am getting the problem in the renderProducts() method.

/// <reference path="coin.ts" />
/// <reference path="product.ts" />
/// <reference path="productFactory.ts" />

enum VendingMachineSize {
  small = 6,
  medium = 9,
  large = 1,
}

class Cell {
  constructor(public product: CocoCola) {}
  stock: 3;
  sold: false;
}

class VendingMachine {
  private totalMoney = 0;
  private totalMoneyText = <HTMLSpanElement>document.getElementById("total-money");
  private containerElement = <HTMLDivElement>document.querySelector(".machine");
  allCoins: number[] = [0];
  cells = [];
  selectedCells = [new Cell(new CocoCola())];

  set size(givenSize: VendingMachineSize) {
    this.cells = [];

    for (let index = 0; index < givenSize; index  ) {
      let product = ProductFactory.GetProduct();
      this.cells.push(new Cell(product));
    }
    this.renderProducts();
  }

  constructor() {
    console.log("I am vending machine!");
  }

  select(cell: Cell) {
    cell.sold = false;
    this.selectedCells.push(cell);
    console.log(this.selectedCells);
  }

  acceptCoin(coin: Quarter): void {
    this.totalMoney  = coin.Value;
    this.totalMoneyText.textContent = this.totalMoney.toString();
  }

  renderProducts() {
    this.cells.forEach((product) => {
      let html = `<div  style="width: 18rem">
        <img src=${product.product.category.getImageUrl()}  alt="..." />
        <div >
          <h5 >${product.product.name}</h5>
          <p >
           ${product.product.description}
          </p>
          <button type="button"   onclick="machine.select(${product})">           
  • Related