Angular 17:表格渲染异常及SSR下按钮失效问题求助
表格渲染异常修复求助
表格未能正常渲染,SSR环境下问题更严重,尤其是Product组件中的“Add To Cart”按钮。我希望保留独立的Product组件(正在学习Angular组件间通信相关知识),目标是实现一个常规表格,每行显示一个商品的属性。
我尝试过将<tr>标签从app组件移到product组件,但导致所有行显示在同一行;也考虑过在product组件中添加<table>标签为每行单独创建表格,但担心会因名称和价格长度不同导致行对齐错乱。
以下是相关代码:
app.component.ts
import { Component } from '@angular/core'; import { ProductComponent } from './product/product.component'; import { CartComponent } from './cart/cart.component'; import { Product } from './product'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-root', standalone: true, imports: [ProductComponent, CartComponent, CommonModule], templateUrl: './app.component.html', styleUrl: './app.component.css', }) export class AppComponent { readonly products: Product[] = [ new Product('Flamethrower', 100), new Product('Pillow', 200), new Product('Book', 300), ]; cartItems: Product[] = []; addToCart(product: Product) { this.cartItems.push(product); } }
app.component.html
<h2>Products</h2> <table> <thead> <th>Name</th> <th>Price</th> <th>Action</th> </thead> <tbody> <tr *ngFor="let product of products"> <app-product [product]="product" (addToCartEvent)="addToCart($event)" ></app-product> </tr> </tbody> </table> ...
app.component.css
table, th, td { border: 1px solid black; }
product.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { Product } from '../product'; import { isPlatformServer } from '@angular/common'; @Component({ selector: 'app-product', standalone: true, templateUrl: './product.component.html', styleUrl: './product.component.css' }) export class ProductComponent { @Input() product!: Product; @Output() addToCartEvent = new EventEmitter<Product>(); addToCart() { this.addToCartEvent.emit(this.product); } }
product.component.html
<td>{{ product.name }}</td> <td>{{ product.price }}$</td> <td><button (click)="addToCart()">Add To Cart</button></td>
内容的提问来源于stack exchange,提问作者Ammar Rangwala
相关产品推荐
相关产品推荐

