0
votes

I am very new to Angular 2. We are developing a menu based angular app using router-outlet.

I have a field in App.component.html, let say - JobName , which is binded using a property in app.component.ts and ng-model attribute.

User can go to a menu (say, SelectNewJob ) and can select a new Job. SelectNewJob is another component loaded using router-outlet tags

When User change job in SelectNewJob tab, I need to Update JobName field in app.component.html.

How can I do this.? I have tried Event Emitters, but it not working with router-outlet. Is there any other way to achieve this (using service..etc)

Please help.

1
Use a service or try to use ngrx to keep a global state - JEY

1 Answers

0
votes

One of simple ways to solve this problem is service. You can place some Subject there and subcribe to it in components. Service body will look like so:

private jobName: Subject<string> = new Subject<string>();

public get _jobName(): Observable<string> {
  return this.jobName.asObservable();
}

public updateJobName(name: string): void {
  this.jobName.next(name);
}

don't forget about imports

and in your components you cant do something like this

public jobName: string = '';

constructor(private jobService: JobService) {}

ngOnInit() {
  this.jobService._jobName.subscribe((name: string) => {
    this.jobName = name;
 }
}

public updateName(newName: string): void { 
  this.jobService.updateJobName(newName);
}

where JobService is the name of you service

this approach will solve your problem , but don't forget to cleanup subscriptions in ngOnDestroy()