How to send data from parent to child and vice-versa

Forums AngularHow to send data from parent to child and vice-versa
Staff asked 3 years ago

data sharing between parent component and child component

Answers (1)

Add Answer
monika gabani Marked As Accepted
Staff answered 2 years ago

Angular provide @Input Decorator and @Output Decorator to share data between parent to child and child to parent component.

The @Input Decorator is used to configure the input properties of the component.

app-parent.component.html

<div>
<h2>Hii</h2>
<h2>{{message}}</h2>
</div>

<app-chlid (event)=”message=$event” [parentdata]=”name”></app-child>

In app-parent.component.ts add following:

export class AppComponent {
title = ‘InputOutput’;
public name = “Code Hub”
public message =””;
}

In app-child.component.ts file add following:

export class TestComponent implements OnInit {

constructor() { }

ngOnInit(): void {
}
@Input(‘parentdata’) public name:any;
@Output() public event = new EventEmitter();

fireEvent(): void {
this.event.emit(‘Hey Angular…’);
}
}

In app-child.component.html file add following:

<h2>{{name}}</h2>

<button (click)=”fireEvent()”>send</button>

hear, name property of parent component use in child component to display name and when click on send button of child it send data using @Output decorator to parent component.

Thanks.

 

 

 

 

 

 

 

Subscribe

Select Categories