【发布时间】:2019-01-23 06:08:00
【问题描述】:
我正在尝试用 Angular 创建一个基本应用程序,但遇到了以下问题。我有一个组件,其中列出了我拥有的所有食谱,每个食谱都有不同的数据。我为每个配方添加了一个按钮,它打开了一个带有特定对象附加信息的模式,至少这是计划。现在,无论我点击哪个按钮,我总是显示相同的数据。 我能否就如何继续并始终显示正确的数据提供一些提示?对于 recipe2 -> recipe2 数据.. 现在我正在显示所有其他食谱的食谱 1 数据。
这是组件:
<div class="col my-3">
<div class="card">
<img [src]="recipe.imagePath" alt="{{ recipe.name }}" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ recipe.name }}</h5>
<p class="card-text">{{ recipe.preview }}</p>
<div class="row">
<div class="col text-center">
<button type="button" class="btn btn-outline-primary" data-toggle="modal" data-target="#recipeModal">
Read More...
</button>
</div>
</div>
<div class="modal fade" id="recipeModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">{{ recipe.name }}</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>{{ recipe.description }}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-success">Add to List</button>
<button type="button" class="btn btn-outline-warning">Edit</button>
<button type="button" class="btn btn-outline-danger">Delete</button>
</div>
</div>
</div>
</div>
<!-- <app-recipe-detail></app-recipe-detail> -->
</div>
<div class="card-footer">
<small class="text-muted">Posted by: Random Name</small>
</div>
</div>
还有打字稿文件:
import { Component, OnInit, Input } 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() { }
ngOnInit() {
}
}
这是我在列表组件中显示所有食谱的方式:
<div class="row">
<app-recipe-item *ngFor="let recipeItem of recipes" [recipe]="recipeItem"></app-recipe-item>
</div>
提前致谢!
【问题讨论】:
-
你有多少食谱?只有两个?首先,您似乎只有一个按钮来显示食谱详细信息。我建议您创建与您拥有的食谱数量一样多的按钮(仅当您想将一个按钮专用于单个食谱时)。为此,您需要将配方 ID 与按钮绑定。您在按钮中声明的
#recipeModal,我在其他任何地方都找不到。您应该改为从按钮中的文件中获取配方 id 值并将 id 传递给您的模态。尝试使用带有两个单独 id 的两个单独按钮。 -
是的,很抱歉我编辑了我的帖子 - 我将所有这些项目都放在一个列表组件中,我使用 ngFor 来显示所有这些项目。
标签: angular components