Sandra Willford
Sandra Willford

Reputation: 3789

@Output event emitter not working

I have a child component that emits an event like such...

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

@Component({
    selector: 'app-rate-sort',
    templateUrl: './rate-sort.component.html'
})
export class RateSortComponent implements OnInit {

    @Output() sort = new EventEmitter<string>();

    constructor() { }

    ngOnInit() {
    }

    sortBy(string) {
        this.sort.emit(string);
    }

}

this should be passing the string invoked by a button on the template to the parent like such...

<header class="bg-white">
    <h4 class="text-primary my-0 mr-3">Media List Builder</h4>
    <div class="inner">
        ...
        <div class="wrapper">
            <app-rate-sort (onSort)="onSort($event)"></app-rate-sort>
        </div>
    </div>
    <div class="utility">
        ...
    </div>
</header>

and then in the parent component, i have a simple method for handling the event...

onSort(event) {
    this.sortKey = event;
    console.log(event);
}

however it seems that the parent is not getting the event, as the output in console is empty.

What am I missing here?

Upvotes: 2

Views: 17602

Answers (3)

Sajeetharan
Sajeetharan

Reputation: 222722

To fix,

Your output should be

@Output() onSort = new EventEmitter<string>();

also

sortBy(string) {
        this.onSort.emit(string);
 }

EDIT

As per angular guidelines, don't use on with the ouput. just rename your event method as sort.

<div class="wrapper">
            <app-rate-sort (sort)="onSort($event)"></app-rate-sort>
 </div>

Upvotes: 3

Anuradha Gunasekara
Anuradha Gunasekara

Reputation: 6983

You are trying to get a event from a onSort event. But there is no event emmiter in your class for that.

you should change your parent component's template to this.

<div class="wrapper">
       <app-rate-sort (sort)="onSort($event)"></app-rate-sort>
</div>

Upvotes: 0

Jay
Jay

Reputation: 406

The event name has changed when you used it in the parent component.

Try (sort) not (onSort)

<header class="bg-white">
    <h4 class="text-primary my-0 mr-3">Media List Builder</h4>
    <div class="inner">
        ...
        <div class="wrapper">
            <app-rate-sort (sort)="onSort($event)"></app-rate-sort>
        </div>
    </div>
    <div class="utility">
        ...
    </div>
</header>

Upvotes: 2

Related Questions