Ron
Ron

Reputation: 593

angular 2 output and eventemitter doesn't emit

i'm learning angular 2, and i follow this tutorial: https://egghead.io/lessons/angular-2-angular-2-building-a-toggle-button-component but the whole part of the output and eventemitter doesn't work. i do not get any errors and i can't figure out why it doesn't work.

this is my code for the togglelink component:

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



@Component({
  moduleId: module.id,
  selector: 'app-togglelink',
  templateUrl: 'togglelink.component.html',
  styleUrls: ['togglelink.component.css']
})
export class TogglelinkComponent implements OnInit {

  @Input() state:boolean = true;
  @Output() onChange = new EventEmitter();

  onClick(){
    this.state = !this.state;
    this.onChange.emit(this.state);
  }

  constructor() {}

  ngOnInit() {
  }

}

and this is the code for the firstpage component that uses the togglelink component: import { Component, OnInit } from '@angular/core'; import {TogglelinkComponent} from '../togglelink/togglelink.component';

@Component({
  moduleId: module.id,
  selector: 'app-firstpage',
  templateUrl: 'firstpage.component.html',
  styleUrls: ['firstpage.component.css'],
  directives: [TogglelinkComponent]
})
export class FirstpageComponent implements OnInit {

  thetogglestate:boolean = false;

  firsttitle = "the first title";
  constructor() {}

  ngOnInit() {
  }

}

and this is the code for the template of the firstpage component: {{thetogglestate ? 'On' : 'Off'}}

</p>
<h2 *ngIf="thetogglestate">
  {{firsttitle}}
</h2>
<p>
  firstpage works!
</p>

when i change manually thetogglestate it does work, so i understand that the issue is with the output and the eventemitter part.

any idea why?

best regards

Upvotes: 0

Views: 2623

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202306

In the firstpage.component.html template, you need to register some processing for this event to toggle the value of the thetogglestate variable.

Something like that:

<app-togglelink (onChange)="thetogglestate = !thetogglestate"></app-togglelink>

Upvotes: 2

Related Questions