0

The below code is not running in Angular 11.2.12. where as it is working in angular 6.0.3

product.component.ts Component class

 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>

When I am running this I am seeing error message below

Error: src/app/product/product.component.html:3:19 - error TS2339: Property 'id' does not exist on type 'Object'.

3

{{product.id}}

~~

src/app/product/product.component.ts:5:16 5 templateUrl: './product.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component ProductComponent.

Error: src/app/product/product.component.html:4:19 - error TS2339: Property 'name' does not exist on type 'Object'.

4

{{product.name}}

~~~~

src/app/product/product.component.ts:5:16 5 templateUrl: './product.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component ProductComponent.

I tried <div *ngFor="let product of getProducts()">

2
  • Can you try and add safe operator on the products? like so {{product?.id}} {{product?.name}} ? Commented May 7, 2021 at 7:37
  • You declared projects as type Object[] thus the compiler is looking for a 'name' or 'id' attribute on your products which it does not find. Try declaring it as any[] if you don't want to provide type information or use an interface that represents your products. Commented May 7, 2021 at 7:44

1 Answer 1

2

You have to change type of products from object to below:

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

That is because Angular introduced Template type checking from version 9.x which has 3 different modes basic, full and strict. You can find more information on the Angular website as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Devang. worked for me. Is there are any chnages from Agular 6.0.3 to 11.2.12 in declartion?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.