Search code examples
angulartypescripteventemitter

what is eventemitter and eventemitter service. How we use Event emitter without @output and @input?


I'm new to the angular2 and i'm confused about the EventEmitter using EmitterService can anyone explain me the purpose of Emitter.

And Without using @input and @output can we send the data to one page component to another page component.

Thanks


Solution

  • Read this Angular cookbook about component interaction and flow, especially this part about parent components listening for child events.

    Basically, EventEmitters are intended exactly for the purpose of parent components getting data from children. All @Outputs are EventEmitters and the @Output decorator exposes an event that parents can attach listeners to in its template.

    In the child component, you define an EventEmitter like so:

    @Output() childEventEmitter = new EventEmitter<any>();
    

    You emit events like this:

    this.childEventEmitter.emit("Send this to the parent");
    

    With that done, the parent can listen for the event and attach a callback with nothing more than this:

    <child-component (childEventEmitter)="parentCallback(whateverWasEmitted)"></child-component>
    

    It makes (child -> parent) communication as easy as normal hierarchical data flow (parent -> child). You may or may not have noticed that when you send information from parent to child, tbe parent binds to the child's @Input properties in the template with [square brackets]. When a parent receives information from the child, in its template, it binds to the child's @Output events with (parenthesis). This is an important principle in Angular 2.

    @Input() is to properties is to [square brackets] as @Output() is to events is to (parenthesis).

    To answer your other question, yes, it is possible for components that aren't directly 'next' to each other in the component hierarchy to communicate, but in this case, a common instance of an Angular 2 service is required to act as a middle-man of sorts. Read this section of the Angular 2 cookbook I linked to before to learn more about that.

    See also: Very helpful video about Angular 2 data flow