由於ingredient model會有數個component共享,所以將之放入共享資料夾,會較適合。
結構:
app
|-- shared
|--- ingredient.model.ts
ingredient.model.ts內容:
export interface Ingredient {
name: string;
amount: number;
}
在shopping-list新增ingredient陣列
ingredients: Ingredient[] = [
{ name: 'apple', amount: 5 },
{ name: 'orange', amount: 10 },
];
使用ngFor顯示資料
<div class="row">
<div class="col-10">
<app-shopping-edit></app-shopping-edit>
<hr>
<div class="list-group">
<a class="list-group-item list-group-item-action" style="cursor: pointer;" *ngFor="let ingredient of ingredients">
{{ ingredient.name }} ({{ ingredient.amount }})
</a>
</div>
</div>
</div>
顯示:
shopping-edit.component.html內容:
<div class="row">
<div class="col-12">
<form>
<div class="form-row">
<div class="form-group col-sm-5">
<label for="name">Name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group col-sm-2">
<label for="amount">Amount</label>
<input type="number" class="form-control" id="amount">
</div>
</div>
<div class="row">
<div class="col-12">
<button class="btn btn-success mr-2" type="submit">Add</button>
<button class="btn btn-danger mr-2" type="button">Delete</button>
<button class="btn btn-primary" type="button">Clear</button>
</div>
</div>
</form>
</div>
</div>
顯示: