You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 10:18:11