【问题标题】:Angular2 eventEmitter, parent wont catch itAngular2 eventEmitter,父母不会抓住它
【发布时间】: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


    【解决方案1】:

    这段代码真的没有意义

    @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' 这样的选择器

    【讨论】:

    • 它是一个组件.. 很抱歉造成混淆。
    • 请从组件中删除@Injectable()。你只需要它来提供服务,而不是当其他装饰器如@Component()@Directive()@Pipe() 已经存在时。这些装饰器包括@Injectable()
    • 好的,完成了。我并没有真正遵循您要告诉我的内容。现在我正在使用路由,并加载 home 组件,例如:
    • 我试图告诉您解决代码问题。这并不意味着这些肯定能解决你的问题,但我不想在明显的问题得到解决之前浪费我的精力去寻找微妙的问题;-)
    • 你也不能在&lt;router-outlet&gt;上收听。您需要一个共享服务来与路由器添加的组件进行通信。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多