Home > Software design >  Passing modal form data to another component not working in Angular
Passing modal form data to another component not working in Angular

Time:02-18

I have a modal (popup) and there is a form in that. When user fills that form and hit the Add button, I want to pass that form values to the component where is it showing.(result)

I tried it as below but it doesn't executing the this.modalRef.content.onClose.subscribe method. Can someone point out the issue here?

myComponent.ts

modalRef?: BsModalRef | null;
constructor(private modalService: BsModalService) { }

addItem(): void{
      const initialState = {
            backdrop: true,
            ignoreBackdropClick: true,
            class: 'modal-xl',
          };

          this.modalRef = this.modalService.show(ItemProfileComponent, { ...initialState, backdrop: true, ignoreBackdropClick: true, class: 'modal-lg', });
          this.modalRef.content.onClose.subscribe((result: any) => {
            console.log(result); 
            if (result) {
              this.itemtList.push(result);
              this.itemAdd.emit(this.itemtList);
            }
          });

  }

ItemProfileComponent.ts (Modal Component)

public onClose: Subject<any> | undefined;
constructor(private bsModalRef: BsModalRef) {}

  ngOnInit(): void {
    this.onClose = new Subject();
  }
     close(): void {
      this.bsModalRef?.hide();
    }

ItemProfileComponent.html

<div >
    <h4  id="my-modal-title">Add New<span *ngIf="isItem"> Item</span></h4>
    <button role="button"  aria-label="Close" (click)="close()">
        <span aria-hidden="true" >&times;</span>
    </button>
</div>
    
    <div >
        <div >
     <!--Form-->
        <div *ngIf="!isCompany">
            <app-contact-profile [isContactHeader] = "false" [contactData] = "agentContactList" (saveContact) = "addAgentContact($event)"></app-contact-profile>
        </div>
    </div>
</div>

CodePudding user response:

You forgot to call next(), pass your form data as a parameter. You should also call complete() to unsubscribe all subscriptions.

close(): void {
   this.onClose.next(formData);
   this.onClose.complete();
   this.bsModalRef?.hide();
}

That's assuming you want to send the data on every close, you may want a separate function for when the user just wants to cancel. ie. a submit() and a close().

  • Related