13

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?

2 Answers 2

22

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I have a similar issue and I'm putting it in the correct place unable to solve this
4

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

<app-navbar (showEvent)="getToggle($event)"></app-navbar>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.