skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search