我试图从组件中选择多个对象,并仅显示父组件中的选定对象。我想从子组件进行api调用,从子组件中选择特定对象,然后在父组件中显示它们。目前,我只能使用* ngFor循环显示api中的所有对象,但我想选择特定对象并在父组件中列出这些对象。
item.component.html
<div class="pull-right">
<button class="btn btn-success" (click)="addItem()">Add New Item</button>
</div>
<br>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of Items" [class.active]="item === selectedItem" (click)="onSelect(item)">
<td>{{item.itemName}}</td>
<td>{{item.description}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div *ngIf="selectedItem">
<h2>
{{selectedItem._id}} is my item
</h2>
</div>
</div>
item.component.ts(子)
export class ItemComponent implements OnInit {
Items: Item[];
selectedItem: Item;
constructor(
private router: Router,
private itemService: ItemService){}
getItems(){
this.itemService.getItems()
.then(Items => this.Items = Items);
}
ngOnInit(){
this.getItems();
}
onSelect(item: Item){
this.selectedItem = item;
}
估计-detail.component.ts
export class EstimateDetailComponent implements OnInit {
@Input() estimate: Estimate;
@Input() item: Item;
Items:Item[];
constructor(
private estimateService: EstimateService,
private itemService:ItemService,
private route: ActivatedRoute) {
}
ngOnInit() {
this.getItems();
}
getItems(){
this.itemService.getItems()
.then(Items => this.Items = Items);
}
估计-detail.component.html(父)
<tbody>
<tr *ngFor=" let item of Items">
<td>
<a cart-button [item]="item" action="remove" class="btn btn-default btn-sm"> X </a>
</td>
<td><b>{{item.itemName}}</b><br>{{item.description}}</td>
</tr>
</tbody>