Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular @Output & EventEmitter not working

Tags:

angular

I am trying to pass the value of show from my navbar component to my app root component which i am using to form the basic layout of the app. In the navbar-component.ts I have this:

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

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html'
})
export class NavbarComponent {

    public show = true;
    @Output() showEvent = new EventEmitter<boolean>();

    constructor() { }

    sendToggle() {
        if (this.show === true) {
            this.show = false;
        } else {
            this.show = true;
        }
        this.showEvent.emit(this.show);
    }

}

and then in the template I have this:

<button type="button" class="btn btn-transparent ml-2 mr-auto"
    (click)="sendToggle()">
    <span class="fa fa-bars"></span>{{ show }}
</button>

I added {{ show }} just so that I can see the state of show change per the sendToggle() method.

Then I set up the app-component.ts like this to listen for the event:

import { Component } from '@angular/core';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})

export class AppComponent {

    public show: boolean;

    getToggle($event) {
        this.show = $event;
    }

}

and then on the template I have this:

<app-navbar></app-navbar>
<div id="wrapper">
    <nav (showEvent)="getToggle($event)" id="sidebar" [ngClass]="{show: show}">
        {{ show }}
        <app-sidebar></app-sidebar>
    </nav>
    <div id="content">
        <app-breadcrumb></app-breadcrumb>
        <router-outlet></router-outlet>
    </div>
</div>

so when I click the button I can see the state of show change within the navbar component, however the app component does not seem to be getting the message. What the heck am I doing wrong here?

like image 218
Sandra Willford Avatar asked Jan 06 '18 21:01

Sandra Willford


Video Answer


2 Answers

You should put the showEvent on the actual component selector app-navbar that has the @Output decorator and not on the nav element:

<app-navbar (showEvent)="getToggle($event)"></app-navbar>
like image 131
Poul Kruijt Avatar answered Sep 19 '22 23:09

Poul Kruijt


You've got your handler on the wrong element (nav instead of app-navbar)

<app-navbar (showEvent)="getToggle($event)"></app-navbar>
like image 34
David Avatar answered Sep 19 '22 23:09

David