I have two components, One parent and Other Child.
HTML Part
<div> <div class="row col-md-12"> <div class="col-md-4"> <!-- Some HTML Code of Parent component over here --> </div> <div class="col-md-8"> <child-component></child-component> </div> </div> <button class="button" (click)="reloadOnlyChild($event)">Reload Child</button> </div>
Now, On click of this button, I want the only child to get reload, or refresh.
TS Part
reloadOnlyChild(event){ // I want to reload the child from here. }
I searched on the Internet, I am getting for Vue or React, But not for Angular.
There is button by which i am updating my page data. on button click i have save data in back end and refresh data. So to reload/refresh the component - as per my requirement - is only to refresh the data. if this is also your requirement then use the same code written in constructor of component.
To refresh, or better to say update another component from a different component, we can use the concept of Observables and Subject (which is a kind of Observable). This concept has an added benefit when data are to be received from APIs for CRUD operations.
Best way to update a child component is: ngOnChanges()
ngOnChanges(): "A lifecycle hook that is called when any data-bound property of a directive changes. Define an ngOnChanges() method to handle the changes." We use this lifecycle hook to respond to changes to our @Input() variables.
Example:
import { Component, Input, OnChanges } from "@angular/core"; @Component({ selector: "child-component", templateUrl: "./child-component.html" }) export class MyComponent implements OnChanges { @Input() someInput: string; constructor() {} ngOnChanges() { /**********THIS FUNCTION WILL TRIGGER WHEN PARENT COMPONENT UPDATES 'someInput'**************/ //Write your code here console.log(this.someInput); } }
Use child component inside parent component as follows
<child-component [someInput]="inputValue"></child-component>
Say if you have a form in Child.Component.ts
and if you want to reset it from parent component
you can establish a connection between parent and child using Subject
.
Parent.Component.html
<child-component [resetFormSubject]="resetFormSubject.asObservable()"></child-component> <button (click)="resetChildForm()"></button>
Parent.Component.ts
import { Subject } from "rxjs"; resetFormSubject: Subject<boolean> = new Subject<boolean>(); resetChildForm(){ this.resetFormSubject.next(true); }
Child.Component.ts
import { Subject } from "rxjs"; @Input() resetFormSubject: Subject<boolean> = new Subject<boolean>(); ngOnInit(){ this.resetFormSubject.subscribe(response => { if(response){ yourForm.reset(); // Or do whatever operations you need. } } }
By using Subject you can establish a connection from parent to the child whenever the button gets clicked.
Hope this answer helps! Cheers :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With