How to reload or refresh only child component in Angular 8

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 :)


You could add an Input to update the component, or add a update function in the child that you can call in the code. Using @ViewChild to call the child update function from the parent. Like this

( https://stackblitz.com/edit/angular-updatechild ):

Child:

import { Component } from "@angular/core";

@Component({
   selector: "app-child",
   templateUrl: "./child.component.html",
   styleUrls: ["./child.component.css"] 
})
export class ChildComponent {
   ticks = Date.now().valueOf();

   constructor() {}

   update(): void {
   this.ticks = Date.now().valueOf();
   }
}

Parent:

import { Component, OnInit, ViewChild } from "@angular/core";
import { ChildComponent } from "./../child/child.component";

@Component({
 selector: "app-parrent",
 templateUrl: "./parrent.component.html",
 styleUrls: ["./parrent.component.css"]
})
export class ParrentComponent implements OnInit {
  @ViewChild(ChildComponent, { static: false }) childC: ChildComponent;
  showChild: boolean = true;
  constructor() {}

  ngOnInit() {}

  onUpdateChild() {
    this.childC.update();
 }
}

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>