I've been at this for some time, many articles, the documentation, much trial and error but I feel I'm missing something core.
Essentially I'm trying to create an extensible navigation component that other components can add items to when they are added to the page. I've tried to accomplish this a couple ways, including a service, this example I'm attempting it by injected one component into another component.
I have a component with a list of items in it, I have an ngFor that loops through the items and displays text. I have a button on the page that when you click adds an item to the array. I also have injected the component into another component that I have add an item to the array on NgOnInit() (tried other lifecycle events and in the constructor).
The strangeness is that when the button adds the items to the array the list updates but when the other component adds the items the list it does not update the UI even though the count of items is incremented and I can see in the UI the component has already loaded and rendered the default items.
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.
SidebarComponenta Component or a Service? - Eric Martinez