LadyT
LadyT

Reputation: 659

Angular 2: Event Emitter not working properly

I have two components. I have a help menu component and a navigation component. When a user clicks the help button, it should show the help menu. I made a variable called help in the app component. In the nav component, I made an event emitter to try two-way binding, but it doesn't work on the nav component. I am kinda confused because the variable help only works when the app loads, but not when I click the help button.

app component.ts

help:boolean = true;

App component html

<!-- app menu div -->
<app-help [(helps)]="help"></app-help>

<!-- app navigation -->
<app-nav [help]="help"></app-nav>

App-nav component html

<button class="circle" (click)="helpMenu()">H</button>

App-nav component.ts

export class NavComponent implements OnInit{

@Input() help:boolean;
@Output() HelpsChange: EventEmitter<boolean> = new EventEmitter<boolean>();

constructor(){}

// when user clicks the help button
helpMenu(){
    this.help = true;
    this.HelpsChange.emit(this.help);
 }
}

App-help component.html

<div id="helpMenu" *ngIf="help==true">
<p>Help</p>
<button (click)="closeHelp()">Close</button>

App-help component.ts

export class HelpComponent implements OnInit {

@Input()  help:boolean;
@Output() helpsChange: EventEmitter<boolean> = new EventEmitter<boolean>();

constructor() { }

ngOnInit() {
}

closeHelp(){
 this.help = false; 
 this.helpsChange.emit(this.help);
}

}

Upvotes: 1

Views: 2130

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208944

Not just changing the [(helps)] to [(help)] like Fabio mentioned, but you also need to change the name of the variable in the directive to remove the s from helpsChange. It's important that the input and output follow the naming format property/propertyChange, when you when you want to use the "banana in a box" syntax [()]

Upvotes: 2

Related Questions