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

Angular项目不使用*ngFor展示单个客户报价数据的实现问题

解决方案

1 修改TS组件代码

你需要先从接口返回的报价数组中提取出要展示的单个报价对象,修改后的代码如下:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '@environments/environment';
import { Quote } from '@app/_models/quote';
import { Router, ActivatedRoute } from '@angular/router'; // 引入ActivatedRoute用于接收路由参数

@Component({
  selector: 'app-quote-summary',
  templateUrl: './quote-summary.component.html',
  styleUrls: ['./quote-summary.component.css']
})
export class QuoteSummaryComponent implements OnInit {

    apiUrl: string = environment.apiUrl
    quotes: Quote[]
    currentQuote: Quote // 新增:存储当前要展示的单个报价
    //TODO: implement submitted quote view later
    //submittedQuotes: Quote[]

    constructor(
      private http: HttpClient, 
      private router: Router,
      private route: ActivatedRoute // 注入路由
    ) { }
 
    ngOnInit(): void {
        this.getQuotes()
    }
    // #region API Calls

    getQuotes() {
        var httpRequest = this.http.get<Quote[]>(`${this.apiUrl}/quotes`)

        httpRequest.subscribe(returnedQuotes => {
            this.quotes = returnedQuotes
            // 方式1:直接取数组第一条报价展示
            this.currentQuote = returnedQuotes[0]
            
            // --- 如果需要展示指定ID的报价,用以下代码替换上面的赋值即可 ---
            // const targetQuoteId = this.route.snapshot.queryParams['quoteId'] // 取路由query参数里的报价ID
            // this.currentQuote = returnedQuotes.find(item => item.id === targetQuoteId)
        })
    }

}

2 修改HTML模板代码

删除原有*ngFor循环,直接绑定currentQuote的属性,原有布局结构完全保留,不影响你设定的相邻排布规则:

<hr />
<div class="info">
    <div id="CustomerInfoInline" *ngIf="currentQuote" >
        <h6>Name: {{currentQuote.firstName}} {{currentQuote.lastName}}</h6>
        <h6>Address: {{currentQuote.address}}</h6>
        <h6>City, State, Zip: {{currentQuote.city}}, {{currentQuote.state}}, {{currentQuote.zip}}</h6>
        <h6>SSN: {{currentQuote.SSN}}</h6>
        <h6>DOB: {{currentQuote.dateOfBirth}}</h6>
        <h6>Email: {{currentQuote.email}}</h6>
        <h6>Prev. Carrier: {{currentQuote.previousCarrier}}</h6>
        <h1>-----------------------------------------------------------------------------------------------</h1>
    </div>

    <div *ngIf="currentQuote">
        <div id="CustomerDiscountsInline">
            <h6 id="customerBold">Customer Discounts</h6>
            <h4 id="DiscountsID">discounts will be applied here</h4>
        </div>
    </div>
</div>
<hr />

注意事项

  • 模板判断条件从quotes改为currentQuote,可以避免数据未加载完成时的渲染报错
  • 原有循环中重复的id属性问题在改为单个展示后自动修复,符合HTML规范

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:36:03