【问题标题】:Angular2 Output/emit() not workingAngular2输出/发射()不工作
【发布时间】:2016-08-18 20:50:08
【问题描述】:

对于我的一生,我无法弄清楚为什么我不能发出或捕获一些数据。 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 的建议。

【问题讨论】:

    标签: javascript angular typescript angular2-directives


    【解决方案1】:

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

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

    应用组件

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

    Forked Plunkr

    【讨论】:

    • 我不敢相信我把$event 丢了。我做了更正,仍然没有。我确实注意到console.log() 没有启动。所以我认为(toggle)="toggleNavigation($event) 没有触发。
    • @Mike 你能在我的回答中找到附加的 plunkr,谢谢 :)
    猜你喜欢
    • 2018-10-20
    • 2015-10-15
    • 1970-01-01
    • 2017-04-12
    • 2017-11-23
    • 2017-03-03
    • 2016-08-15
    • 2017-04-29
    • 2017-09-20
    相关资源
    最近更新 更多