In Angular, you can send data from a child component to its parent component using an @Output
property and an event emitter. Here's an example:
In the child component:
Import
EventEmitter
andOutput
from@angular/core
:pythonimport { Component, EventEmitter, Output } from '@angular/core';
Declare an
@Output
property with an event emitter:java@Output() dataEvent = new EventEmitter<string>();
In this example, the
dataEvent
property is an@Output
property that emits an event with a string value.Emit the event with the data you want to send:
kotlinthis.dataEvent.emit('Hello from child component!');
In this example, the
emit()
method is called on thedataEvent
property to emit an event with the string value'Hello from child component!'
.
In the parent component:
Add the child component to the parent component's template:
bash<app-child (dataEvent)="onDataEvent($event)"></app-child>
In this example, the
app-child
component is added to the parent component's template, and an event binding is set up with thedataEvent
property of the child component.Define a method to handle the event in the parent component:
typescriptonDataEvent(eventData: string) { console.log('Received data from child component:', eventData); }In this example, the
onDataEvent()
method is defined to handle the event emitted by the child component. TheeventData
parameter is the data that was emitted by the child component.
When the child component emits the dataEvent
event, it will trigger the onDataEvent()
method in the parent component, and pass the emitted data as the event parameter. The parent component can then handle the data as needed.
Angular, Angular Interview Question and Answers, Angular Tutorial,
Comments
Post a Comment