Angular 2 - 一个组件触发页面上另一个组件的刷新

标签 angular typescript angular2-components

我有一个组件ComponentA,它显示元素列表。此列表在 ngOnInit 期间初始化。

我有另一个组件 ComponentB 提供可能影响 ComponentA 中显示的元素列表的控件。例如。可以添加一个元素。

我需要一种方法来触发 ComponentA 的重新初始化。

有人有想法吗?


详情

A 是带有显示“savedSearchs”列表的菜单的 HeaderBar

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

B 是一个可以保存搜索的 SearchComponent

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

最佳答案

您需要提供组件,并将其注入(inject)到组件的构造函数中,您需要像我一样调用其他组件的 ngOnInit。

Plunker 演示: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 {}

关于Angular 2 - 一个组件触发页面上另一个组件的刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40282646/

相关文章:

javascript - angular 2 - ngFor 动态函数

html - 具有可扩展行的 Angular Material 表,在更改选项卡时自动扩展以 stackBlitz 示例

css - 如何增加 Angular 8 中 mat-dialog-actions 的宽度

reactjs - Promise.all 错误 - 类型 '(Video | undefined)[]' 无法分配给类型 'Video[]'

typescript - 泛型:TS2345 'T[keyof T]' 类型的参数不可分配给 'Date' 类型的参数,其中 <T extends {}>

angular - 在 Angular 2 中测试 ngOnChanges 生命周期钩子(Hook)

Angular2 如何更改禁用按钮的颜色

angular - ngFor 中的动态组件

angular - 如何使用rxjs进行多个内部嵌套订阅

css - 由于@Font-Face 在 Chrome 中呈现问题