简体   繁体   中英

Update Parent Property When Child Property Changes in Angular2 ( Child component loaded using router-outlet)

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM