Angular 2 - Updating one component with a trigger for another component on the page

I have a ComponentA component that displays a list of elements . This list is included in ngOnInit .

I have another ComponentB component that provides controls that can affect the list of items shown in ComponentA. EG. item can be added.

I need a way to cause ComponentA to restart.

Does anyone have any ideas?


More details

A is a HeaderBar with a menu that displays a 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 ability to save searches

 @Component({ selector: 'search', templateUrl: 'app/search/search.html' }) export class SearchComponent implements OnInit { ... } 
+12
source share
1 answer

You need to provide the component and enter it inside the component constructor, where you need to call ngOnInit of another component, like me.

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 {} 
+10
source

Source: https://habr.com/ru/post/1258884/


All Articles