已经使用了相当一段时间了,试图找出父母没有收到事件并调用函数的原因。Angular2 eventEmitter,父母不会捕获它
有一个父应用程序(称为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>
这里我使用的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:
是否有人在这里,看到我做了什么错?
其选择的成分..遗憾的混淆。 – Mikkel
请从组件中删除'@Injectable()'。你只需要它的服务,但不是像@Component(),@ @ Directive()','@Pipe()'等其他装饰器已经在那里。这些装饰器包括'@Injectable()' –
好的,做到了。我并没有真正关注你想告诉我的事情。 现在我正在使用路由,并加载家庭组件如: router-outlet> –
Mikkel