Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Angular 4中使用ngFor向数组添加内容并输出_Angular - Fatal编程技术网

在Angular 4中使用ngFor向数组添加内容并输出

在Angular 4中使用ngFor向数组添加内容并输出,angular,Angular,我一直忙于基本任务,即尝试更新数组并输出相应的值。这影响了整个应用程序 我把我的问题简化为以下几点。首先,我创建了以下模型: export class Recipe { public name: string; public description: string; public imagePath: string; constructor(name: string, desc: string, imagePath: string) { this.name = name;

我一直忙于基本任务,即尝试更新数组并输出相应的值。这影响了整个应用程序

我把我的问题简化为以下几点。首先,我创建了以下模型:

export class Recipe {
  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;
  }
}
然后,我继续向recipes组件添加内容:

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('NAME', 'DESC','URL1'),
    new Recipe('NAME2', 'DESC2','URL2')
   ];

   constructor() {
   }

   ngOnInit() {
   }
}
然后,我以以下方式使用*ngFor:

 <a 
  href="#"
  class="list-group-item clearfix"
  *ngFor="let recipe of recipes">
  <div">
    <h4 class="list-group-item-heading">{{ recipe.name }}</h4>
    <p class="list-group-item-text">{{ recipe.description }}</p>
  </div>
  <span>
    <img
      src="{{ recipe.imagePath }}"
      alt="{{ recipe.name }}"
      class="img-responsive"
      style="max-height: 50px;">
  </span>
</a>
我已经研究了其他问题,例如,但是我无法相应地实施解决方案

更改阵列值时,无法在浏览器上看到更改

如何使用*ngFor添加新配方并使其在浏览器中可见


任何关于我缺少什么核心功能的建议都将不胜感激

我为您的问题创建了工作演示:

模板:


我会这样做:

recipes : Recipe[] = [];
recipe : Recipe;

ngOnInit() {
 this.recipes.push(this.recipe = {name: 'asd'}, 
                   this.recipe = {name: 'asf'});
 console.log(this.recipes);
}

我认为它不太容易出错,因为如果您更改Recipe的任何属性,这将有助于调试,因为您可以看到为属性名称分配了什么值:“asd”

您在组件中尝试过这个.recipes.pushnew Recipe'NAME2'、“DESC2'”和“URL2”了吗?是的,但运气还不好。在这种情况下,我似乎缺少一些基本的东西。您能添加更多与RecipeListComponent相关的代码吗?也许配方数组引用有一些问题…现在我可以复制并修复它。。。请看我的答案
recipes : Recipe[] = [];
recipe : Recipe;

ngOnInit() {
 this.recipes.push(this.recipe = {name: 'asd'}, 
                   this.recipe = {name: 'asf'});
 console.log(this.recipes);
}