0

Let's say I want to implement a lightbox component, which uses <dialog> to render its content. Something like:

@Component({
  selector: 'image-popup',
  template: `
  <dialog>
  ...
  </dialog>
`
})
export class ImagePopupComponent {
...
  show(): void {
    this.element.nativeElement.showModal();
  }
}

If I create an instance of this in the main app component, how can I enable its access from other components. For eg., in some descendant component, I have a button where I want the click to trigger show() on this dialog instance. In my use case, this component will have an imageUrl property, and the same component will be used multiple times to show different images.

2
  • Use a shared service. There are tons of similar questions with answers. Commented Feb 20, 2016 at 15:54
  • 1
    Martin's comment below looks correct. Please note that by default service injections are singletons. So you'll be receiving the same instance of 'MyModalService' in all your components. Commented Feb 20, 2016 at 21:38

1 Answer 1

2

You can use a service for this.

@Injectable()
export class MyModalService {
    component: MyModal;
}

@Component({
    selector: 'my-modal',
})
export class MyModal {
    constructor(private element: ElementRef, modalService: MyModalService) {
        modalService.component = this;
    }

    show(): void {
        this.element.nativeElement.showModal();
    }
}

Then in some other component:

@Component({
    selector: 'another',
})
export class AnotherComponent {
    constructor(private _modalService: MyModalService) {
    }

    buttonClicked() {
        this._modalService.show();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

With this method, will the MyModal template render automatically ? For exemple if MyModal use a bootstrap modal, and I use this.element.nativeElement.modal(), will the bootstrap modal appear automatically ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.