问题描述
我有一个组件 ComponentA ,它显示元素列表.此列表在ngOnInit
期间初始化.
I have a component ComponentA that displays a list of elements. This list is inited during ngOnInit
.
我有另一个组件 ComponentB ,它们提供的控件可能会影响ComponentA中显示的元素列表.例如.可以添加一个元素.
I have another component ComponentB providing controls that might influence the list of elements shown in ComponentA. E.G. an element may be added.
我需要一种方法触发ComponentA的重新初始化.
有人有主意吗?
详细信息
A 是一个HeaderBar,其菜单显示"savedSearchs"列表
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 是一个SearchComponent,可以保存搜索
B is a SearchComponent with the possibility to save searches
@Component({
selector: 'search',
templateUrl: 'app/search/search.html'
})
export class SearchComponent implements OnInit {
...
}
推荐答案
您需要提供组件,并将其注入到组件的构造函数中,像我一样,您需要调用其他组件的ngOnInit.
You need to provide component, and inject it inside constructor of component where you need to call ngOnInit of other component like I did.
柱塞演示: 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 {}
这篇关于角度2-一个组件触发页面上另一组件的刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!