I’ve seen many, many examples on how to pass data to a modal –
const modalRef = this.modalService.open(NgbdModalContent);
modalRef.componentInstance.data = 'World';`
And then intercepting it in ngOnInit
@Input() public data;
constructor() {}
ngOnInit(): void {
console.log(this.data);
}
However, what If the data is async? The order things are being called just feels wrong to me, we’re calling open, then after opening we’re setting ‘data’?
This is in one of the official examples of how to pass data, but I’m just weary to use it because it feels like a race condition waiting to happen. Maybe I’m not understanding certain things under the hood, very new to angular.
What I’d like to do is pass this data upfront to ‘open’, or do something only when that property is fully set inside my modal component.
I’ve tried tying into ngOnChanges() and it wasnt detecting the input was being mutated.
I also wonder if its not just easier to use a service I pass around between components (injected through each constructor) and just set data to that.
In this case, the data is not async, but it still just feels very off to me to call open, and afterwards pass data…
Any help understanding very much appreciated.
2
Answers
You can think of the above pattern as "opening a door" and then "passing the groceries into that door". The modal has to be open in order to be able to accept data.
I would concur with you that using a service would be a good alternative. Then the components could pull in the data when they need it instead of getting "pushed" data.
And lastly, just an opinion, but I don’t think modals are very "web" like and try to avoid them whenever possible. Instead just using normal components and route guards to ask things like "save before you go?".
It’s the same another component. You do, e.g.
Or you have
And in your component you have
Or use pipe async in the .html of the component
NOTE: In your component always can to have a
*ngIf="data"
to show a squeleton or the data