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?
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>
You've got your handler on the wrong element (nav instead of app-navbar)
<app-navbar (showEvent)="getToggle($event)"></app-navbar>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With