Im trying to learn angular and Im following a code tutorial and as far as I can tell my code matches the instructors but it's not working.
I have the following code and it fails to compile saying the objects dont exist. what am i missing?
import { ThrowStmt } from '@angular/compiler';
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 Details:
<div *ngFor="let product of products">
<h1>{{product.name}}</h1>
<h1>{{product.id}}</h1>
</div>
it prints out [[object Object]] twice if i remove the.name and.id, but as it stands i get the following errors.
4 <h1>{{product.name}}{{product.id}}</h1>
~~~~
src/app/product/product.component.ts:6:16
6 templateUrl: './product.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component ProductComponent.
Error: src/app/product/product.component.html:4:35 - error TS2339: Property 'id' does not exist on type 'Object'.
4 <h1>{{product.name}}{{product.id}}</h1>
~~
SOLVED I have solved the issue by changing from Object[] to any[].
products:any[];
this solved the issue.
You have to specify products
type as the array with strongly typed class/interface instead of Object[]
;
product.model.ts
export interface Product {
id: string;
name: string;
}
product.component.ts
import { Product } from '../models/product.model';
products: Product[];
Sample Solution 1 on StackBlitz
Alternative, change the text interpolation as below if you prefer products
as Object[]
type.
<div *ngFor="let product of products">
<h1>{{product["name"]}}</h1>
<h1>{{product["id"]}}</h1>
</div>
Try using ?
operator, like this:
<div *ngFor="let product of products">
<h1>{{product?.name}}</h1>
<h1>{{product?.id}}</h1>
</div>
Your current code will break if any product is missing name
or id
property.
The issue was using the type Object[] Swapping to any[] solved the issue.
Change products:Object[]; to products:any[]; Ie the type should be any instead of Object. this is a general angular bug. Hope they resolve it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.