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

时光毁灭记忆、已成空白 提交于 2019-12-23 06:59:02

问题


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 {
  ...
}

回答1:


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 {}


来源:https://stackoverflow.com/questions/40282646/angular-2-one-component-trigger-refresh-of-another-component-on-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!