Search code examples
angularangular6angular5angular7angular8

How to reload or refresh only child component in Angular 8


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.


Solution

  • 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>