[英]Angular2 eventEmitter, parent wont catch it
现在已经使用了相当长的时间,试图找出父级为什么不接收该事件并调用该函数。
有一个父应用程序(称为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 hastittet”)行; 正在被调用,因此它应该发送事件。
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)” (应在AppComponent.ts中调用该方法)之后,在这里使用ngFor
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交互 :
有人在这里看到我做错了吗?
这段代码真的没有意义
@Injectable()
export class HomeComponent {
@Output() selected = new EventEmitter<boolean>();
它是一个组件,那么它需要一个@Component(...)
装饰器,而不是@Injectable()
装饰器。
如果是服务,则不能有@Output()
如果它实际上是一个组件,那么您只能收听此组件
<home-component (selected)="selected($event)"></home-component>
不在任意元素上。 这不会监听选择的@Output() selected ...
<div class="basket_products" *ngFor="#product of products" (selected)="selected($event)">
除了当HomeComponent
具有类似选择器selector: '.basket_products'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.