How do trigger a component to render in Angular 2 after update property via another component? ngZone.run() is not working

I am having a problem getting a component to re-render. I have a breadcrumb component that I want other components to be able to update it by calling a method. E.g. say I have a ViewContact component, I want that component to set the active page in the breadcrumb to be the name of the contact.

The breadcrumb component is being injected into the ViewContact component & I’ve set up the provider for the breadcrumb. The ViewContact component is calling a method on the breadcrumb component which is in turn calling ngZone.run() as I’ve read should trigger the component to re-render. However it isn’t.

I’ve created a simple Plunker here: http://plnkr.co/edit/rWZ8ZGqmda1cieDmsc2s

Is what I’m trying to do achievable using injection or is there a better way?

Thanks….

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

In your case you can’t inject the Breadcrumb component into the OtherComponent one since they don’t have a parent / child relation. This won’t work even if you add the first component into providers: providers: [Breadcrumb], Either you choose the approach provided by G√ľnter, either you choose a shared service: import {Subject} from 'rxjs/Rx'; export class SharedService { property:string; property$:Subject<string> = new Subject(); setProperty(newValue:string) { this.property = newValue; this.property$.next(this.property); } } In the components you will use this service this way: export class OtherComponent implements OnInit { count: number = 1; constructor( private service: SharedService) { } ngOnInit() { this.updateBreadcrumb();… Read more »

Jason
Guest

You can use an EventEmitter and template variables to communicate between siblings.

export class OtherComponent implements OnInit {
  @Output() notifyOther:EventEmitter = new EventEmitter();

  ...

  updateBreadcrumb() {
    this.notifyOther.emit("changed " + (this.count++));
    //this._breadcrumb.setProperty("changed " + (this.count++));
  }
}
<breadcrumb #breadCrumb></breadcrumb>

<other-component (notifyOther)="breadCrumb.testProperty = $event"></other-component>

Plunker example