Angular 14子组件数据未在父组件中显示问题求助
Angular 14 子组件数据不显示问题解决
问题核心错误
父组件模板的*ngFor循环中,你给<app-card>的[mydata]绑定了整个数组projData,而非当前循环的单个项目proj,导致子组件无法读取正确的单条数据结构。另外异步数据加载时未处理空值,也可能引发潜在报错。
修正步骤
1. 修复父组件模板的绑定错误
将父组件模板中<app-card>的绑定值从projData改为proj,同时添加空值检查确保数据加载后再渲染:
<div class="flex items-center justify-center bg-background2 h-full w-full mb-0 text-gray-100 "> <div class="max-w-6xl mx-auto "> <header class="flex flex-col items-center justify-center"> <p class="text-6xl font-bold pb-[1rem]">Solutions I have crafted</p> <p class="text-lg pb-[2rem] text-center ">A list of the projects that I have worked on ranging from multiple languages and frameworks.</p> </header> <!-- 添加*ngIf确保数据加载完成后再渲染列表 --> <main class="grid grid-cols-3" *ngIf="projData"> <div class="flex flex-col border-[1px] border-accent px-6 py-8 rounded-md" *ngFor="let proj of projData"> <!-- 绑定当前循环的单个项目数据 --> <app-card [mydata]="proj"></app-card> </div> </main> </div> </div>
2. 优化父组件的数据类型定义(可选但推荐)
避免使用any类型,给projData定义明确的类型,提升代码可读性和类型检查能力:
import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; // 定义项目数据的类型接口 interface Project { title: string; description: string; } @Component({ selector: 'app-projects', templateUrl: './projects.component.html', styleUrls: ['./projects.component.css'] }) export class ProjectsComponent implements OnInit { projData!: Project[]; constructor(private http: HttpClient) { } ngOnInit(): void { this.http.get<Project[]>('../assets/data.json').subscribe(mydata =>{ this.projData = mydata; console.log(this.projData) }) } }
3. 子组件模板添加空值安全(可选)
为避免数据未加载完成时的控制台报错,可在子组件模板中使用可选链操作符:
<span class="flex gap-4 items-center"> <svg class="iconsboxed" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"> <path d="M13.5 3a.5.5 0 0 1 .5.5V11H2V3.5a.5.5 0 0 1 .5-.5zm-11-1A1.5 1.5 0 0 0 1 3.5V12h14V3.5A1.5 1.5 0 0 0 13.5 2zM0 12.5h16a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 0 12.5"/> </svg> <span class="text-lg">{{mydata?.title}}</span> </span> <p class="text-sm text-gray-400 py-4">{{mydata?.description}}</p>
说明
修正后,父组件会遍历数组中的每个proj对象,将单条数据传递给子组件,子组件就能正确读取title和description字段并渲染。异步数据的空值处理也能避免初始加载阶段的报错问题。
内容的提问来源于stack exchange,提问作者muhumuza amb
相关产品推荐
相关产品推荐

