Reputation: 129
Recently, I am trying Angular5 and I would like to know the best practice for triggering events in other component.
So this is my application structure right now:
index.html
<main-app></main-app>
app.component.html
<main-navbar></main-navbar>
<router-outlet></router-outlet>
<auth-modal></auth-modal>
auth modal component
import { Component, EventEmitter } from '@angular/core';
@Component({
selector: 'auth-modal',
templateUrl: 'modal.component.html'
})
export class AuthModal {
hidden: boolean = true;
closed: EventEmitter<any> = new EventEmitter();
close(event: KeyboardEvent){
this.hidden = !this.hidden;
this.closed.next(true);
event.stopPropagation();
}
}
So main-navbar component is basically html, no logic inside. What I am trying to approach is, building custom modal (like bootstrap), so when I click a button in navbar it triggers modal component and it opens.
Rather than code, I would like which approach should I follow.
I have searched about this, but I do not like to use third party packages, since the main purpose is to learn instead of achieving desired result.
SOLUTION
Thanks to https://stackoverflow.com/users/6036154/embarq and https://stackoverflow.com/users/271012/ryan I got the solution here : https://angular-jswxqi.stackblitz.io/
Upvotes: 0
Views: 737
Reputation: 335
I propose you to implement service for controlling the modal. Prototype for this service could be
enum ModalState { Close, Open }
class ModalController {
public readonly modalState$: Subject<ModalState>;
constructor() {
this.modalState$ = new Subject<ModalState>();
}
public open() {
this.modalState$.next(ModalState.Open);
}
public close() {
this.modalState$.next(ModalState.Close);
}
}
So this minimal implementation can be used as follows:
ModalController.modalState$
and handles changesModalService.open
and ModalService.close
can be used by any components in the whole appUpvotes: 2
Reputation: 12357
One approach is to use a Service that emits events and that can be subscribed to also. Provide the service in AppModule, and inject it into the modal, which listens for the event, and into any component that might trigger the modal to display.
If you want there is also the Angular Material CDK (component development kit), which has a Portal and PortalHost - purposely built for injecting things like modals into the DOM
Upvotes: 1