Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Output/emit() not working

For the life of me I cannot figure out why I cannot either emit or capture some data. The toggleNavigation() fires, but I'm not sure if the .emit() is actually working.

Eventually I want to collapse and expand the navigation, but for now I just want to understand how to send data from the navigation.component to the 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');
    }
}

EDIT

I added Pankaj Parkar's suggestions.

like image 213
Mike Avatar asked Feb 07 '23 08:02

Mike


1 Answers

You just need to specify $event parameter on method, so whatever emitted on navToggle output value, that data will be available inside AppComponent 'stoggleNavigationmethod$event` parameter.

<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

like image 193
Pankaj Parkar Avatar answered Feb 10 '23 23:02

Pankaj Parkar