0

I am creating a generic modal component that has the usual attributes to be passed: title, content (using <ng-content></ng-content>), and customization for buttons.

My question is if I am filling the content of the modal as a form, and this form needs validation before closing the modal, how can we make the validator stop the modal from closing?

I saw in these answers that it is not recommended for passing a function to the component to use @Input and the better way is using @Output which actually accesses the parent function instead of passing it. But that does not allow me to stop the modal from closing, the code looks like this now:

in parent.component.html:

<app-modal title="test" (callback)="validator()"> ...form content ...</app-modal>

in modal.component.ts:

  @Output() callback: EventEmitter<any> = new EventEmitter();
  onConfirm(): void {
    this.callback.emit();
    // here I should stop the execution in case the validation did not pass
    this.onClose.next(1);
    this.modalRef.hide(); // using ngx-bootstrap modal

}

I can not get a return value from the callback .

Is there a clean way to achieve this without using @Input for passing functions?

sisimh
  • 1,287
  • 3
  • 20
  • 37
  • Can you have an output that notifies that the user clicked something to initiate a close (an output) but have the parent pass a variable (an input) on if the model should be open or not? – Daniel W Strimpel Apr 12 '18 at 02:54
  • @DanielWStrimpel, is there a cleaner way to do so, to avoid the mess in the design – sisimh Apr 12 '18 at 15:11
  • That IS the clean way. You are asking a parent component to be in charge of whether to close the modal or not. You need to notify the parent of an action and let the parent determine what to do. You could instead of having an input to say whether to open or close it instead provide public methods on your component to open or close it and the parent component could call those directly, but it feels like the cleaner way would to just notify the component to do that via an input. – Daniel W Strimpel Apr 12 '18 at 15:33

0 Answers0