2

I have a requirement in Angular2 where I need to open a first popup and the user would enter some values. On some user event i.e. a button click I need to close that popup and open another popup with the values pre-populated entered by the user in the first popup.

I have created a plunker where I have created a Login component which is my first popup and Home component which is the second popup. On entering the user credentials it should navigate to the home component. I am bit struck here i.e. how to pass the username values from the first popup to the second, also how to close the first and load the second popup?

Can anyone help me with this issue, and let me know what are the changes need to be done in my plnkr?

export class LoginModal implements CloseGuard, ModalComponent<CustomModalContext> {
  context: CustomModalContext;

  public username: string;
  public password: string;

  constructor(public dialog: DialogRef<CustomModalContext>, public modal: Modal) {
    this.context = dialog.context; // this is the dialog reference
    dialog.setCloseGuard(this);
  }

  openHome()
  {
     return this.modal.open(HomeModal,  overlayConfigFactory({ username }, BSModalContext));
  }
}
Krishnan
  • 896
  • 3
  • 19
  • 40
  • Create a User service and inject that into both Login and Home component and use it to make the data available to both - https://angular.io/docs/ts/latest/tutorial/toh-pt4.html – glendaviesnz Jun 11 '17 at 04:01

1 Answers1

0

You need to store your login component values in a share injectable service by creating a variable in it.

Service

@Injectable()
export class SharedService {
  public sharedValues:any;
}

App Module

@NgModule({
imports: [BrowserModule,
      HttpModule],
declarations: [AppComponent],
providers: [SharedService],
bootstrap: [AppComponent]
}) export class AppModule { }

Access the values in your both login and home component like below:

import {SharedService} from 'path of service folder';
export class LoginModal {

constructor(private sharedService:SharedService) {
}

 click() {
  this.sharedService.sharedValues // get and set your values
 }
}

Note: Don't set the providers for SharedService in the components, otherwise it won't become shared

Jayakrishnan
  • 3,724
  • 2
  • 17
  • 29
  • Can you please answer the other part of the question also, i.e. how to close the first popup and load the second one? do I need to have routing configured or any other better way to handle it? – Krishnan Jun 11 '17 at 15:07
  • @Krishnan, you need to subscribe to variable changes in the service in the app.component and act accordingly. Please check https://stackoverflow.com/questions/35869406/angular2-detect-change-in-service, it has the solution for your case – Jayakrishnan Jun 11 '17 at 15:18