Home > OS >  Angular Parent to Child Data Sending
Angular Parent to Child Data Sending

Time:02-01

How to send data on a button click event from parent to child ?

I was sending data from parent to child using a button click event but i unable to send

CodePudding user response:

In Angular, you can send data from a parent component to a child component using property binding:

// Parent component
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <app-child [message]="message"></app-child>
    <button (click)="sendMessage()">Send Message</button>
  `
})
export class ParentComponent {
  message = 'Hello from parent';

  sendMessage() {
    this.message = 'Message sent from parent';
  }
}

// Child component
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <p>{{ message }}</p>
  `
})
export class ChildComponent {
  @Input() message: string;
}

ParentComponent has a property message that is bound to a message input in the ChildComponent using the square bracket syntax [message]. The ParentComponent also has a sendMessage method that changes the value of message when a button is clicked. The ChildComponent displays the value of message in its template. When the button is clicked, the message value is updated in the ParentComponent and automatically passed down to the ChildComponent through property binding.

CodePudding user response:

You can solve this in couple of ways:

  1. use @Input() someVariable in the child component then
<app-parent>
<app-child  [someVariable]="dataOnClickChange">    <app-child>
</app-parent>

that is good if the data on the click is changing.

  1. use service and listen for changes/events. Just subscribe to it and in order to pass the click you can use observable or behavioralSubject with next()

More information on:

data binding

observable

behavioralSubject

Live example

why you need to pass the click event to child component in the first place maybe there is a better way to accomplish what you need.

  • Related