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:
- 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.
- use service and listen for changes/events. Just
subscribe
to it and in order to pass the click you can useobservable
orbehavioralSubject
withnext()
More information on:
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.