Angular 2 - One component trigger refresh of another component on the page

Philipp picture Philipp · Oct 27, 2016 · Viewed 29.6k times · Source

I have a component ComponentA that displays a list of elements. This list is inited during ngOnInit.

I have another component ComponentB providing controls that might influence the list of elements shown in ComponentA. E.G. an element may be added.

I need a way to trigger a reinit of ComponentA.

Does someone have an idea?


Details

A is a HeaderBar with a menu that shows the list of "savedSearchs"

@Component({
  selector: 'header-bar',
  templateUrl: 'app/headerBar/headerBar.html'
})
export class HeaderBarComponent implements OnInit{
  ...
  ngOnInit() {
    // init list of savedSearches
    ...
  }
}

B is a SearchComponent with the possibility to save searches

@Component({
  selector: 'search',
  templateUrl: 'app/search/search.html'
})
export class SearchComponent implements OnInit {
  ...
}

Answer

Rohan Fating picture Rohan Fating · Sep 3, 2017

You need to provide component, and inject it inside constructor of component where you need to call ngOnInit of other component like I did.

Plunker Demo : https://plnkr.co/edit/M0d65wHjfg4KfwaQ5mPM?p=preview

//our root app component
import {Component, NgModule, VERSION, OnInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
       <comp-one></comp-one>
       <comp-two></comp-two>
    </div>
  `,
})
export class App {
  name:string;
  constructor( ) {
    this.name = `Angular! v${VERSION.full}`
  }
}

// ComponentOne with ngOnInit

@Component({
  selector: 'comp-one',
  template: `<h2>ComponentOne</h2>`,
})
export class ComponentOne implements OnInit {

  ngOnInit(): void {
    alert("ComponentOne ngOnInit Called")
  }

}

// Added provider of ComponentOne here and injected inside constructor the on button click call ngOnInit of ComponentOne from this component
@Component({
  providers:[ComponentOne],
  selector: 'comp-two',
  template: ` Component Two: <button (click)="callMe()">Call Init of ComponentOne</button>`,
})
export class ComponentTwo implements OnInit {

   constructor(private comp: ComponentOne ) {
    this.name = `Angular! v${VERSION.full}`
  }
  public callMe(compName: any): void {
    this.comp.ngOnInit();
  }


}
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, ComponentOne, ComponentTwo ],
  bootstrap: [ App ]
})
export class AppModule {}