I have been doing this for a while, a lot of articles, documentation, a lot of trial and error, but I feel like I'm missing something.
Essentially, I'm trying to create an extensible navigation component that other components can add to elements when they are added to the page. I tried to do this in several ways, including a service, in this example I am trying to do this by injecting one component into another component.
I have a component with a list of elements in it, I have ngFor, which iterates over the elements and displays the text. I have a button on the page that, when clicked, adds an element to the array. I also added the component to another component, which I add to the array in NgOnInit () (I tried other life cycle events in the constructor as well).
The strange thing is that when the button adds elements to the array, the list is updated, but when another component adds elements to the list, it does not update the user interface, even if the number of elements increases and I see in the user interface the component has already loaded and displayed the default elements .
import {Component} from 'angular2/core';
import {Router, RouteParams} from 'angular2/router';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {Injectable} from 'angular2/core';
@Component({
selector: 'caseBasedSearchSidebar',
template: `<ul id="sidebar-wrapper" class="clearfix nav navbar-default sidebar-nav">
<li *ngFor="#nav of navigationItems">
<span>{{nav.name}}</span>
</li>
<ul> <button (click)=addNavigationItem()>Add</button> `,
directives: [ROUTER_DIRECTIVES] })
@Injectable() export class SidebarComponent {
public navigationItems: Array<ISideNavigationItem>;
constructor() {
this.navigationItems = [{ name: 'test' }];
}
public addNavigationItem(item: ISideNavigationItem) {
this.navigationItems.push({ name: 'test' });
}
}
export interface ISideNavigationItem {
name: string; }
import {Component, OnInit} from 'angular2/core';
import {SidebarComponent} from '../sideBar.component';
@Component({
templateUrl: '/CaseBasedSearch/PatientInformation',
providers: [SidebarComponent]
})
export class PatientInformationComponent implements OnInit {
private sideBarComponent: SidebarComponent;
constructor(sideBarComponent: SidebarComponent) {
this.sideBarComponent = sideBarComponent;
}
ngOnInit() {
this.sideBarComponent.addNavigationItem({ name: 'testing' });
}
}
Any guidance is appreciated.
source
share