【发布时间】:2016-07-22 16:47:58
【问题描述】:
已经用了好久,试图找出为什么父级没有收到事件并调用函数。
拥有一个父应用(称为 AppComponent)和子组件(称为 HomeComponent)
HomeComponent.ts
@Component({
selector: 'home-component',
providers: [],
moduleId: module.id,
encapsulation: ViewEncapsulation.None,
templateUrl: 'home.component.html',
styleUrls: ['home.component.css'],
directives: [BannerComponent],
})
export class HomeComponent {
@Output() selected = new EventEmitter<boolean>();
products: Array<Product> = [];
isProductSelected: boolean = false;
constructor(public productService: ProductService) {
}
addProductToBasket(product: Product) {
// Add product to basket.
this.productService.addProduct(product);
this.isProductSelected = true;
if (this.isProductSelected) {
console.log("Event has been emittet");
this.selected.emit(this.isProductSelected);
//Sets to default
this.isProductSelected = false;
}
}
}
我想在产品添加到购物篮时通知父组件。检查控制台,可以看到 console.log("Event has been emittet"); 行正在被调用,所以它应该发送事件。
AppComponent.html
<aside class="aside" [ngClass]="{'aside-active': isClassVisible }">
<div class="basket_products" *ngFor="#product of products">
</div>
</aside>
<router-outlet (selected)="selected($event)"></router-outlet>
在我尝试使用 (selected)="selected($event)" 之后,我在这里使用 ngFor,它应该调用 AppComponent.ts 中的方法
AppComponent.ts
selected(selected: boolean)
{
console.log("Event catches");
if (selected) {
// Get new data
this.totalProducts = this.productService.getTotalProducts();
this.totalprice = this.productService.getTotalProductPrice();
this.shippingPrice = this.productService.getShippingPrice();
}
}
问题是该方法永远不会被调用。
已尝试按照您在此处看到的步骤“父母侦听子事件”Angluar2 interactions:
这里有人知道我做错了吗?
【问题讨论】:
标签: angular eventemitter