Search code examples
angulareventemitter

Child component not emitting value to parent component's function


I have defined a function called login inside my parent component:

login(user: any) {
  console.log(user);
}

Then I have a login form component:

export class LoginFormComponent {
  @Output() onLogin: EventEmitter = new EventEmitter();

  constructor() {
    this.user = {};
  }
}

Which I use like this:

<login-form (onLogin)="login(user)"></login-form>

Which looks something like this:

<input type="email" [(ngModel)]="user.email">
<input type="password" [(ngModel)]="user.password">

And inside this component I have a simple button which should execute the onLogin function and pass the user from login-form component to the outer component:

<button (click)="onLogin.emit(user)">Login</button>

The problem is that user is always undefined in the login function.

Why isn't user getting sent from login-form to my parent component?


Solution

  • The special identifier $event needs to be used to get the emitted value passed:

    <login-form (onLogin)="login($event)"></login-form>
    

    user refers to the user property of the component class.