skip to Main Content

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


  1. 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?".

    Login or Signup to reply.
  2. It’s the same another component. You do, e.g.

    this.id=3
    const modalRef = this.modalService.open(NgbdModalContent);
    this.dataService.getData(this.id).subscribe((x:any)=>{
       modalRef.componentInstance.data = 'World';`
    }
    

    Or you have

       const modalRef = this.modalService.open(NgbdModalContent);
       modalRef.componentInstance.id = 3
    

    And in your component you have

    @Input() public id;
        constructor(dataService:DataService) {}
        ngOnInit(): void {
            this.dataService.getData(this.id).subscribe((x:any)=>{
               this.data = x;
              console.log(this.data);
            }) 
        } 
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search