【发布时间】:2021-07-29 12:10:46
【问题描述】:
以下代码未在 Angular 11.2.12 中运行。它在角度 6.0.3 中工作的地方
product.component.ts 组件类
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
products:Object[];
constructor() {
this.products = [
{
id:"1",
name:"Mac Book Pro"
},
{
id:"2",
name:"Iphone"
}
];
}
public getProducts(){
return this.products;
}
ngOnInit():void {
}
}
product.component.html
Product Details:
<div *ngFor="let product of products">
<h1>{{product.id}}</h1>
<h1>{{product.name}}</h1>
</div>
当我运行它时,我看到下面的错误消息
错误:src/app/product/product.component.html:3:19 - 错误 TS2339:“对象”类型上不存在属性“id”。
3
{{product.id}}
~~src/app/product/product.component.ts:5:16 5 templateUrl: './product.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 组件ProductComponent的模板出错。
错误:src/app/product/product.component.html:4:19 - 错误 TS2339:“对象”类型上不存在属性“名称”。
4
{{product.name}}
~~~~src/app/product/product.component.ts:5:16 5 templateUrl: './product.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 组件ProductComponent的模板出错。
我试过
【问题讨论】:
-
您可以尝试在产品上添加安全操作员吗?像这样
{{product?.id}}{{product?.name}}? -
您将项目声明为 Object[] 类型,因此编译器在您的产品上寻找它找不到的“名称”或“ID”属性。如果您不想提供类型信息或使用代表您的产品的接口,请尝试将其声明为
any[]。
标签: angular