Angular2 Output/emit() 不工作

Angular2 Output/emit() not working

对于我的一生,我无法弄清楚为什么我不能发送或捕获一些数据。 toggleNavigation() 触发,但我不确定 .emit() 是否真的有效。

最终我想折叠和展开导航,但现在我只想了解如何将数据从 navigation.component 发送到 app.component

Here is a Plunker link

app.component

import { Component } from '@angular/core';
import { PasNavigationComponent } from './shared/index';

@Component({
    moduleId: module.id,
    selector: 'pas-app',
    template: `
          <pas-navigation 
            (toggle)="toggleNavigation($event);">
          </pas-navigation>

          <section id="pas-wrapper">
              <pas-dashboard></pas-dashboard>
          </section>              
    `,
    directives: [PasNavigationComponent]
})

export class AppComponent {
    toggleNavigation(data) {
    console.log('event', data);
    }
}

pas-navigation.component

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'pas-navigation',
    template: `
        <nav>
            <div class="navigation-header">
                <i class="fa fa-bars" (click)="toggleNavigation()"></i>
            </div>
        </nav>
    `
    })

export class PasNavigationComponent {

    @Output('toggle') navToggle = new EventEmitter();

    toggleNavigation() {  
        this.navToggle.emit('my data to emit');
    }
}

编辑

我添加了 Pankaj Parkar 的建议。

您只需要在方法上指定 $event 参数,因此无论 navToggle 输出值发出什么,该数据都将在 AppComponent 'stoggleNavigationmethod$ 中可用事件`参数。

<pas-navigation 
    (toggle)="toggleNavigation($event);">
</pas-navigation>

AppComponent

toggleNavigation(data) {
   // you can get emitted data here by `pas-navigation` component
   console.log('event', data);
}

Forked Plunkr