Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - ERROR TypeError: Cannot read property 'name' of undefined when i try to add product

I try to make a basket as simply as possible, I try to add a product to my basket but I have an error but I cannot find my error.

thank you

html

        <h2>Product</h2>
        <div class="card" *ngFor="let product of productList">
            <h1>{{product.name}}</h1>
            <p class="price">{{product.price | currency: 'USD'}}</p>
            <p><button (click)=add()>Add to Cart</button></p>
        </div>
    </div>
    <div>
        <h2>Total</h2>
        <div class="card">
            <table>
                <thead>
                    <tr>
                        <th>product</th>
                        <th>price</th>
                        <th>Quantity</th>
                        <th>total</th>
                    </tr>
                </thead>
                <tbody *ngFor="let added of productArray">
                    <tr>
                        <td>{{added.name}}</td>
                        <td>{{added.price}}</td>
                        <td>x 10</td>
                        <td>45€</td>

ts.file

 productList = [
    { name: 'Louis Vuis', price: 10 },
    { name: 'shubert helmet', price: 20 },
    { name: 'sport gloves', price: 30 }
  ];

  productArray: any = [];

  add(product) {
    this.productArray.push(product);
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your template, you have to change (click)="add()" to (click)="add(product)"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...