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

*ngFor指令与mat-expansion-panel配合失效,寻求解决方案

问题原因与解决方法

问题根源在TypeScript代码的posts变量定义上:你用了类型声明的冒号:,但没有给变量赋值,导致posts实际为undefined,*ngFor无法遍历undefined,直接引发组件故障。

错误代码(TS部分)

posts : [
    { title : "this is first title" , content : "This is 1 content" },
    {title : "this is second title", content : "This is 2 content"},
    {title : "this is third title", content : "This is 3 content"}
];

这里的冒号是用来指定变量类型的,而非赋值,所以posts没有获得数组数据,仅被定义为一个固定长度的元组类型,变量本身未初始化,值为undefined。

修复方法

把冒号:改成等号=,给posts赋予数组值即可:

posts = [
    { title : "this is first title" , content : "This is 1 content" },
    {title : "this is second title", content : "This is 2 content"},
    {title : "this is third title", content : "This is 3 content"}
];

如果需要同时明确类型,可以补充接口定义(可选):

interface Post {
  title: string;
  content: string;
}

posts: Post[] = [
    { title : "this is first title" , content : "This is 1 content" },
    {title : "this is second title", content : "This is 2 content"},
    {title : "this is third title", content : "This is 3 content"}
];

修改后posts拥有了合法的数组数据,*ngFor可以正常遍历,组件就能恢复正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:45:14