Child to Parent Data Passing

In this part, data is sent from child component to parent component.

The list is shown using the child component.

The input field and buttons are in the parent component.

When an action happens in the child, data goes back to the parent.


Select User from Child Component

A function is created in the child component.

This function is called when the Select button is clicked.

whichUser(name: string | undefined){
this.selectedUser.emit(name)
}

The user name is passed when the button is clicked.

<button (click)="whichUser(userName)">Select</button>


Sending Data Using Output and EventEmitter

To send data to the parent, @Output() is used.

An EventEmitter is created in the child component.

The value is sent using emit().

The parent listens to this event using event binding.


(selectedUser)="selectedUser($event)"


Receiving Selected User in Parent

A signal is created in the parent to store the selected user name.

A function receives the value coming from the child.

The signal is updated with the selected name.

selectedUser(name: string) {
this.selectUserName.set(name)
}

The selected user is displayed in the template.

<h3>Selected User {{selectUserName()}}</h3>


Delete User from Child Component

A delete button is added in the child component.

On click, a delete function is called.

delete(name: string | undefined){
this.deleteUser.emit(name)
}

<button (click)="delete(userName)">Delete</button>


Handling Delete in Parent Component

The parent listens to the delete event.

The user name is received as $event.

The users list is updated using filter().

deleteUser(name: string) {
this.users.update((data)=>data.filter((item)=>item!=name))
}

The selected user is removed from the list.


Using Child Component with Events

The child component is used inside a loop.

User name is passed as input.

Select and delete events are handled in the parent.

<app-child
[userName]="user"
(selectedUser)="selectedUser($event)"
(deleteUser)="deleteUser($event)">
</app-child>


Common Mistakes Mentioned

Do not use square brackets for events.

Use $event exactly, do not rename it.

Do not forget new EventEmitter() and emit().

Do not directly call parent functions from child.

Always emit events from the child component.