Hello fellow learners, I am currently diving into the world of Angular and recently stumbled upon the @output decorators in angular. Despite my best efforts to research the topic, I find myself struggling to fully grasp this concept.
Here's a snippet of code to illustrate:
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("This function is 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);
}
}
After some reflection, here is my current understanding regarding this topic:
- The
@output
decorator serves the purpose of transferring data from child components to parent components exclusively. - Upon clicking the button, the function
beingClicked(event)
is triggered and transmits event information via the $event argument. - We are able to emit the event using
this.event.emit(event);
because we have previously instantiated the event within the class with the statement:@Output() event = new EventEmitter();
- Subsequently, the parent component awaits the
(event)
in the app.component.html:<app-tutorials(event)="doSomething($event)"></app-tutorials>
- When the event is emitted from the child component, the function
doSomething($event)
is activated and receives the $event as input.
Question Time:
- Could someone kindly confirm whether my understanding is accurate?
- Furthermore, what exactly does this EventEmitter accomplish and is it always necessary for data transmission upwards?