mohammad maleki
mohammad maleki

Reputation: 74

input decorator in angular does not work properly

I want to bind some properties to the DOM but the @input does not work! no errors in compile time but the browser does not know the properties! note :the browser does not recognize the name ,description and etc properties! note: recipe-item is the child component of recipe-list component!

this is the recipe-list component :

import { Component, OnInit } from '@angular/core';
import { Recipe } from '../recipe.model';
@Component({
  selector: 'app-recipe-list',
  templateUrl: './recipe-list.component.html',
  styleUrls: ['./recipe-list.component.css']
})
export class RecipeListComponent implements OnInit {
  recipes: Recipe[] = [
  new Recipe(
    'a test recipe',
    'this is just a test',
    'some https address')
    ,new Recipe(
      'a test recipe',
      'this is just a test',
      'some https address')];
    constructor() {

  }

  ngOnInit(): void {
  }

}

and this is the recipe-list-component.html file :

<div class="col-xs-12">
        <app-recipe-item 
        *ngFor="let recipeEL of recipes"
        [recipe]="recipeEl"
        ></app-recipe-item>
    </div>

this is the recipe-list component :

import { Component, Input, OnInit } from '@angular/core';
import { Recipe } from '../../recipe.model';
@Component({
  selector: 'app-recipe-item',
  templateUrl: './recipe-item.component.html',
  styleUrls: ['./recipe-item.component.css']
})
export class RecipeItemComponent implements OnInit {
@Input() recipe: Recipe;
  constructor() { 
   console.log(this.recipe)
    }

  ngOnInit(): void {
  }

}

and this is the recipe-item-component html file :

<a href="#" class="list-group-item clearfix">
    <div class="pull-left">
        <h4 class="list-group-item-heading">
            {{recipe.name}}
        </h4>
        <p class="list-group-item-text">
            {{recipe.description}} 
        </p>
    </div>
        <span class="pull-right">
           <img [src]="recipe.imagePath" alt="{{recipe.name}}" class="img-responsive" style="max-height: 50px"> 
        </span>
</a>

Upvotes: 0

Views: 287

Answers (2)

wahab memon
wahab memon

Reputation: 2416

I have created your example in stackblitz, not added the Recipe model but added some dummy data which am able to see. Let me know if this helps.

Upvotes: 0

Karsten
Karsten

Reputation: 389

The problem in this case is that "recipe" is initially undefined. Even if you create it inside the RecipeListComponent, it is not directly passed down to the other component on construction. (Therefore, the console.log will return undefined)

What you could do: Wrap you div inside recipe-item-component html with an *ngIf="recipe"

Upvotes: 1

Related Questions