Home > Enterprise >  Hi, I have created a class with 3 public variables but whenever i try to use String Interpolation i
Hi, I have created a class with 3 public variables but whenever i try to use String Interpolation i

Time:01-29

This is the error i get for the 'imagePath' Property and it is the same for all the other 2 properties:

src/app/recipes/recipe-list/recipe-list.component.html:2:44 - error TS2339: Property 
'imagePath' does not exist on type 'Receta[]'.

2   <img  src="{{recipes.imagePath}}" alt="{{recipes.name}}">
                                         ~~~~~~~~~

  src/app/recipes/recipe-list/recipe-list.component.ts:5:16
   5   templateUrl: './recipe-list.component.html',
                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RecipeListComponent.

This is my recipe.models.ts

export class Receta {
public name: string;
public description: string;
public imagePath: string;

constructor(name: string, desc: string, imagePath: string) {
this.name = name;
this.description = desc;
this.imagePath = imagePath;
}
}

This is my recipe-list.component.ts

 import { Component, OnInit } from '@angular/core';
 import {Receta} from '../recipe.model'
 @Component({
 selector: 'app-recipe-list',
 templateUrl: './recipe-list.component.html',
 styleUrls: ['./recipe-list.component.css']
  })
  export class RecipeListComponent implements OnInit {

  recipes: Receta[] = [
  new Receta('name', 'test', 'url')
   ];

  constructor() { }

  ngOnInit(): void {
  }


  }

And this is the recipe-list.component.html where i try to use string interpolation to display the name, description and image path dynamically

<div  style="width: 18rem;">
<img  src="{{recipes.imagePath}}" alt="{{recipes.name}}">
 <div >
<h5 >{{recipes.name}} </h5>
<p >{{recipes.description}}</p>
<a href="#" >Go somewhere</a>
 </div>
 </div>

  <app-recipe-item></app-recipe-item>

I am new in Angular and typescript so please tell me if im making a silly mistake. Can someone help? Thank you in advance!

CodePudding user response:

Please note that recipes is a list (Receta[]), not a single Receta.

You need to loop through all the recipes if you want to create a card for every one of them. You might find this helpful https://angular.io/api/common/NgForOf

Here's how you'd use it:

<div  style="width: 18rem;" *ngFor="let recipe of recipes">
    <img  src="{{recipe.imagePath}}" alt=" 
    {{recipe.name}}">
    <div >
        <h5 >{{recipe.name}} </h5>
        <p >{{recipe.description}}</p>
        <a href="#" >Go somewhere</a>
    </div>
</div>

CodePudding user response:

replace this line with recipes: Receta[] = [new Receta('name', 'test', 'url') ]; --> recipes: Receta = [new Receta('name', 'test', 'url') ];

recipes is a only a Receta types winngle object

  •  Tags:  
  • Related