Home > database >  How to pass input to a modal dialog in Angular?
How to pass input to a modal dialog in Angular?

Time:11-05

I have a main component UserProfileComponent with a list of items. Attached to this component is a HostListener for the navigation keys on my keyboard to navigate through the list.

While an item in this list is selected, I can open a modal dialog that displays more information about this entry.

THe HostListener from the main component still works while the modal dialog is open and I can navigate through the list in the background. Is there a way to pass the new elements to the already opened modal dialog?

Currently I just pass the items at the beginning, so there is no sync like it would be with a typical Input.

let dialogRef = dialog.open(UserProfileComponent, {
  item: item, <--- item might change after the modal dialog is open
});

CodePudding user response:

Seems like a good scenario where you can use a BehaviorSubject. Initialize it first with some value:

item = new BehaviorSubject<string>('default string');

Now, while invoking the modal dialog:

let dialogRef = dialog.open(UserProfileComponent, {
    item: item.asObservable(), <--- subscribe to this in the dialog
});

Now, whenever you want a new value to be passed in your dialog:

item.next('new string');

Since the dialog component is subscribed to the observable, the new value will get passed.

  • Related