Hello there learning angular and came across the @output decorators in angular. After researching the topic I still have some difficulty wrapping my head around this concept.
Code example:
app.component.html:
<app-tutorials(event)="doSomething($event)"></app-tutorials>
app.component.ts:
import { Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
doSomething(event){
alert("being executed");
}
}
tutorial.component.html:
<button (click)="beingClicked($event)"_>click me</button>
tutorial.component.ts:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-tutorials',
templateUrl: './tutorials.component.html',
styleUrls: ['./tutorials.component.css']
})
export class TutorialsComponent{
@Output() event = new EventEmitter();
beingClicked(event){
this.event.emit(event);
}
}
My current understanding is this, plz correct me if I'm wrong:
outputis used to transfer data only from child components the parent component.- When the button is clicked
beingClicked(event)is fired and passes through event info in the argument with $event. - We can emit the event with
this.event.emit(event);because we first instantiated the event earlier in the class with the statement:@Output() event = new EventEmitter(); - Now the parent component listens for
(event)in the app.component.html:<app-tutorials(event)="doSomething($event)"></app-tutorials> - When the
eventis emitted from the child component thedoSomething($event)function is fired and gets passed in the$event
Question:
- Is my current understanding correct?
- What exactly is this EventEmitter and is it always needed to data upwards?