我正在尝试使用双向绑定来增加Angular 2中的计数器。计数器正确递增,但它会使购物车中的每个项目增加相同的值。我想用它自己的个人计数器增加购物车中的每个项目。我假设我应该使用@ input / @输出来解决这个问题,但我无法解决这个问题。请协助。
估计-detail.component.html
<tr *ngFor=" let item of Items">
<td>
<a cart-button [item]="item" action="remove" class="btn btn-default btn-sm">X</a>
</td>
<td>{{item.itemName}}</td>
<td>{{item.rate}}</td>
<td>
<div class="btn-group">
<custom-counter [(counter)]="counterValue"></custom-counter>
</div>
</td>
<td>${{item.rate*counterValue | number: '.2'}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colSpan="4" class="text-right">Total</td>
<td>${{ items | cartTotal | number: '.2'}}</td>
</tr>
</tfoot>
</table>
</div>
估计-detail.component.ts
@Component({
selector: 'my-estimate-detail',
templateUrl: './app/components/estimateDetail/estimate-detail.component.html'
})
export class EstimateDetailComponent implements OnInit {
@Input() estimate: Estimate;
@Input() item: Item;
@Input() contact: Contact[];
title="Estimate Details";
counterValue = 1;
selectedContact:string;
Items:Item[];
newEstimate = false;
startDate:any;
error: any;
navigated = false; // true if navigated here
constructor(
private estimateService: EstimateService,
private itemService:ItemService,
private route: ActivatedRoute) {
this.startDate = new Date();
}
ngOnInit() {
this.getItems();
this.route.params.forEach((params: Params) => {
let id = params['id'];
if (id === 'new') {
this.newEstimate = true;
this.estimate = new Estimate();
} else {
this.newEstimate = false;
this.estimateService.getEstimate(id)
.then(estimate => this.estimate = estimate);
}
});
}
counter.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'custom-counter',
template: `
<button (click)="decrement()">-</button>
<span>{{counter}}</span>
<button (click)="increment()">+</button>
`
})
export class CustomCounterComponent {
counterValue = 0;
@Output() counterChange = new EventEmitter();
@Input()
get counter() {
return this.counterValue;
}
set counter(val) {
this.counterValue = val;
this.counterChange.emit(this.counterValue);
}
decrement() {
this.counter--;
}
increment() {
this.counter++;
}
}