【问题标题】:Angular code not running in Angular 11.2.12Angular 代码未在 Angular 11.2.12 中运行
【发布时间】: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


【解决方案1】:

您必须将产品类型从对象更改为以下:

products: {id: string, name: string}[];

这是因为 Angular 从 9.x 版本开始引入了模板类型检查,它有 3 种不同的模式 basic、full 和 strict。您也可以在 Angular 网站上找到更多信息。

【讨论】:

  • 谢谢德旺。为我工作。声明中是否有从 Agular 6.0.3 到 11.2.12 的任何更改?
猜你喜欢
  • 1970-01-01
  • 2023-04-05
  • 2017-12-29
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
相关资源
最近更新 更多