Modal

Modal dialogs.

When To Use#

When requiring users to interact with application, but without jumping to a new page to interrupt the user's workflow, you can use Modal to create a new floating layer over the current page for user getting feedback or information purposes. Additionally, if you need show a simple confirmation dialog, you can use NzModalService.confirm(), and so on.

It is recommended to use the Component way to pop up the Modal, so that the component logic of the popup layer can be completely isolated from the outer component, and can be reused at any time. In the popup layer component, you can obtain Modal's component instance by injecting NzModalRef to control the behavior of the modal box.

Examples

Basic modal.

expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-modal-basic',
  template: `
    <button nz-button [nzType]="'primary'" (click)="showModal()"><span>Show Modal</span></button>
    <nz-modal [(nzVisible)]="isVisible" nzTitle="The first Modal" (nzOnCancel)="handleCancel()" (nzOnOk)="handleOk()">
      <p>Content one</p>
      <p>Content two</p>
      <p>Content three</p>
    </nz-modal>
  `,
  styles: []
})
export class NzDemoModalBasicComponent {
  isVisible = false;

  constructor() {}

  showModal(): void {
    this.isVisible = true;
  }

  handleOk(): void {
    console.log('Button ok clicked!');
    this.isVisible = false;
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }
}

To use NzModalService.confirm() to popup confirmation modal dialog. Let NzOnCancel/NzOnOk function return a promise object to delay closing the dialog.

expand codeexpand code
import { Component } from '@angular/core';
import { NzModalRef, NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'nz-demo-modal-confirm-promise',
  template: `
    <button nz-button nzType="info" (click)="showConfirm()">Confirm</button>
  `,
  styles: []
})
export class NzDemoModalConfirmPromiseComponent {
  confirmModal: NzModalRef; // For testing by now

  constructor(private modal: NzModalService) {}

  showConfirm(): void {
    this.confirmModal = this.modal.confirm({
      nzTitle: 'Do you Want to delete these items?',
      nzContent: 'When clicked the OK button, this dialog will be closed after 1 second',
      nzOnOk: () =>
        new Promise((resolve, reject) => {
          setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
        }).catch(() => console.log('Oops errors!'))
    });
  }
}

To customize the text of the buttons, you need to set nzOkText and nzCancelText props.

expand codeexpand code
import { Component } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'nz-demo-modal-locale',
  template: `
    <div>
      <button nz-button nzType="primary" (click)="showModal()">Modal</button>
      <nz-modal
        [(nzVisible)]="isVisible"
        nzTitle="Modal"
        nzOkText="Ok"
        nzCancelText="Cancel"
        (nzOnOk)="handleOk()"
        (nzOnCancel)="handleCancel()"
      >
        <p>Bla bla ...</p>
        <p>Bla bla ...</p>
        <p>Bla bla ...</p>
      </nz-modal>
    </div>
    <br />
    <button nz-button nzType="info" (click)="showConfirm()">Confirm</button>
  `,
  styles: []
})
export class NzDemoModalLocaleComponent {
  isVisible = false;

  constructor(private modalService: NzModalService) {}

  showModal(): void {
    this.isVisible = true;
  }

  handleOk(): void {
    this.isVisible = false;
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  showConfirm(): void {
    this.modalService.confirm({
      nzTitle: 'Confirm',
      nzContent: 'Bla bla ...',
      nzOkText: 'OK',
      nzCancelText: 'Cancel'
    });
  }
}


You can use nzStyle.top or other styles to set position of modal dialog.

NOTE Due to Angular's style isolation, you may need to override the NgZorro style with :: ng-deep within a custom style if encapsulation: ViewEncapsulation.None is not included in the Component

expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-modal-position',
  template: `
    <button nz-button nzType="primary" (click)="showModalTop()">Display a modal dialog at 20px to Top</button>
    <nz-modal
      [nzStyle]="{ top: '20px' }"
      [(nzVisible)]="isVisibleTop"
      nzTitle="20px to Top"
      (nzOnCancel)="handleCancelTop()"
      (nzOnOk)="handleOkTop()"
    >
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
    </nz-modal>

    <br /><br />

    <button nz-button nzType="primary" (click)="showModalMiddle()">Vertically centered modal dialog</button>
    <nz-modal
      nzWrapClassName="vertical-center-modal"
      [(nzVisible)]="isVisibleMiddle"
      nzTitle="Vertically centered modal dialog"
      (nzOnCancel)="handleCancelMiddle()"
      (nzOnOk)="handleOkMiddle()"
    >
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
    </nz-modal>
  `,
  styles: [
    `
      ::ng-deep .vertical-center-modal {
        display: flex;
        align-items: center;
        justify-content: center;
      }

      ::ng-deep .vertical-center-modal .ant-modal {
        top: 0;
      }
    `
  ]
})
export class NzDemoModalPositionComponent {
  isVisibleTop = false;
  isVisibleMiddle = false;

  showModalTop(): void {
    this.isVisibleTop = true;
  }

  showModalMiddle(): void {
    this.isVisibleMiddle = true;
  }

  handleOkTop(): void {
    console.log('点击了确定');
    this.isVisibleTop = false;
  }

  handleCancelTop(): void {
    this.isVisibleTop = false;
  }

  handleOkMiddle(): void {
    console.log('click ok');
    this.isVisibleMiddle = false;
  }

  handleCancelMiddle(): void {
    this.isVisibleMiddle = false;
  }
}

Asynchronously close a modal dialog when a user clicked OK button, for example, you can use this pattern when you submit a form.

expand codeexpand code
import { Component } from '@angular/core';

@Component({
  selector: 'nz-demo-modal-async',
  template: `
    <button nz-button nzType="primary" (click)="showModal()">
      <span>Show Modal</span>
    </button>
    <nz-modal
      [(nzVisible)]="isVisible"
      nzTitle="Modal Title"
      (nzOnCancel)="handleCancel()"
      (nzOnOk)="handleOk()"
      [nzOkLoading]="isOkLoading"
    >
      <p>Modal Content</p>
    </nz-modal>
  `,
  styles: []
})
export class NzDemoModalAsyncComponent {
  isVisible = false;
  isOkLoading = false;

  showModal(): void {
    this.isVisible = true;
  }

  handleOk(): void {
    this.isOkLoading = true;
    setTimeout(() => {
      this.isVisible = false;
      this.isOkLoading = false;
    }, 3000);
  }

  handleCancel(): void {
    this.isVisible = false;
  }
}

To use NzModalService.confirm() to popup a confirmation modal dialog.

expand codeexpand code
import { Component } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'nz-demo-modal-confirm',
  template: `
    <button nz-button nzType="info" (click)="showConfirm()">Confirm</button>
    <button nz-button nzType="dashed" (click)="showDeleteConfirm()">Delete</button>
  `,
  styles: [
    `
      button {
        margin-right: 8px;
      }
    `
  ]
})
export class NzDemoModalConfirmComponent {
  constructor(private modalService: NzModalService) {}

  showConfirm(): void {
    this.modalService.confirm({
      nzTitle: '<i>Do you Want to delete these items?</i>',
      nzContent: '<b>Some descriptions</b>',
      nzOnOk: () => console.log('OK')
    });
  }

  showDeleteConfirm(): void {
    this.modalService.confirm({
      nzTitle: 'Are you sure delete this task?',
      nzContent: '<b style="color: red;">Some descriptions</b>',
      nzOkText: 'Yes',
      nzOkType: 'danger',
      nzOnOk: () => console.log('OK'),
      nzCancelText: 'No',
      nzOnCancel: () => console.log('Cancel')
    });
  }
}

In the various types of information modal dialog, only one button to close dialog is provided.

expand codeexpand code
import { Component } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'nz-demo-modal-info',
  template: `
    <button nz-button (click)="info()">Info</button>
    <button nz-button (click)="success()">Success</button>
    <button nz-button (click)="error()">Error</button>
    <button nz-button (click)="warning()">Warning</button>
  `,
  styles: [
    `
      button {
        margin-right: 8px;
      }
    `
  ]
})
export class NzDemoModalInfoComponent {
  constructor(private modalService: NzModalService) {}

  info(): void {
    this.modalService.info({
      nzTitle: 'This is a notification message',
      nzContent: '<p>some messages...some messages...</p><p>some messages...some messages...</p>',
      nzOnOk: () => console.log('Info OK')
    });
  }

  success(): void {
    this.modalService.success({
      nzTitle: 'This is a success message',
      nzContent: 'some messages...some messages...'
    });
  }

  error(): void {
    this.modalService.error({
      nzTitle: 'This is an error message',
      nzContent: 'some messages...some messages...'
    });
  }

  warning(): void {
    this.modalService.warning({
      nzTitle: 'This is an warning message',
      nzContent: 'some messages...some messages...'
    });
  }
}

Manually destroying a modal.

expand codeexpand code
import { Component } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'nz-demo-modal-manual',
  template: `
    <button nz-button (click)="success()">Success</button>
  `,
  styles: []
})
export class NzDemoModalManualComponent {
  constructor(private modalService: NzModalService) {}

  success(): void {
    const modal = this.modalService.success({
      nzTitle: 'This is a notification message',
      nzContent: 'This modal will be destroyed after 1 second'
    });

    setTimeout(() => modal.destroy(), 1000);
  }
}




Usage of Modal's service, examples demonstrate user-defined templates, custom components, and methods for injecting modal instances.

NOTE If you use Component mode, you need to add your custom Component into declarations and entryComponents for a NgModule

expand codeexpand code
/* entryComponents: NzModalCustomComponent */

import { Component, Input, TemplateRef } from '@angular/core';
import { NzModalRef, NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'nz-demo-modal-service',
  template: `
    <button nz-button nzType="primary" (click)="createModal()">
      <span>String</span>
    </button>

    <button nz-button nzType="primary" (click)="createTplModal(tplTitle, tplContent, tplFooter)">
      <span>Template</span>
    </button>
    <ng-template #tplTitle>
      <span>Title Template</span>
    </ng-template>
    <ng-template #tplContent>
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
      <p>some contents...</p>
    </ng-template>
    <ng-template #tplFooter>
      <button nz-button nzType="primary" (click)="destroyTplModal()" [nzLoading]="tplModalButtonLoading">
        Close after submit
      </button>
    </ng-template>

    <br /><br />

    <button nz-button nzType="primary" (click)="createComponentModal()">
      <span>Use Component</span>
    </button>

    <button nz-button nzType="primary" (click)="createCustomButtonModal()">Custom Button</button>

    <br /><br />

    <button nz-button nzType="primary" (click)="openAndCloseAll()">Open more modals then close all after 2s</button>
    <nz-modal [(nzVisible)]="htmlModalVisible" nzMask="false" nzZIndex="1001" nzTitle="Non-service html modal"
      >This is a non-service html modal</nz-modal
    >
  `,
  styles: [
    `
      button {
        margin-right: 8px;
      }
    `
  ]
})
export class NzDemoModalServiceComponent {
  tplModal: NzModalRef;
  tplModalButtonLoading = false;
  htmlModalVisible = false;
  disabled = false;

  constructor(private modalService: NzModalService) {}

  createModal(): void {
    this.modalService.create({
      nzTitle: 'Modal Title',
      nzContent: 'string, will close after 1 sec',
      nzClosable: false,
      nzOnOk: () => new Promise(resolve => setTimeout(resolve, 1000))
    });
  }

  createTplModal(tplTitle: TemplateRef<{}>, tplContent: TemplateRef<{}>, tplFooter: TemplateRef<{}>): void {
    this.tplModal = this.modalService.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: tplFooter,
      nzMaskClosable: false,
      nzClosable: false,
      nzOnOk: () => console.log('Click ok')
    });
  }

  destroyTplModal(): void {
    this.tplModalButtonLoading = true;
    setTimeout(() => {
      this.tplModalButtonLoading = false;
      this.tplModal.destroy();
    }, 1000);
  }

  createComponentModal(): void {
    const modal = this.modalService.create({
      nzTitle: 'Modal Title',
      nzContent: NzModalCustomComponent,
      nzComponentParams: {
        title: 'title in component',
        subtitle: 'component sub title,will be changed after 2 sec'
      },
      nzFooter: [
        {
          label: 'change component tilte from outside',
          onClick: componentInstance => {
            componentInstance!.title = 'title in inner component is changed';
          }
        }
      ]
    });

    modal.afterOpen.subscribe(() => console.log('[afterOpen] emitted!'));

    // Return a result when closed
    modal.afterClose.subscribe(result => console.log('[afterClose] The result is:', result));

    // delay until modal instance created
    setTimeout(() => {
      const instance = modal.getContentComponent();
      instance.subtitle = 'sub title is changed';
    }, 2000);
  }

  createCustomButtonModal(): void {
    const modal: NzModalRef = this.modalService.create({
      nzTitle: 'custom button demo',
      nzContent: 'pass array of button config to nzFooter to create multiple buttons',
      nzFooter: [
        {
          label: 'Close',
          shape: 'default',
          onClick: () => modal.destroy()
        },
        {
          label: 'Confirm',
          type: 'primary',
          onClick: () =>
            this.modalService.confirm({ nzTitle: 'Confirm Modal Title', nzContent: 'Confirm Modal Content' })
        },
        {
          label: 'Change Button Status',
          type: 'danger',
          loading: false,
          onClick(): void {
            this.loading = true;
            setTimeout(() => (this.loading = false), 1000);
            setTimeout(() => {
              this.loading = false;
              this.disabled = true;
              this.label = 'can not be clicked!';
            }, 2000);
          }
        },
        {
          label: 'async load',
          type: 'dashed',
          onClick: () => new Promise(resolve => setTimeout(resolve, 2000))
        }
      ]
    });
  }

  openAndCloseAll(): void {
    let pos = 0;

    ['create', 'info', 'success', 'error'].forEach(method =>
      // @ts-ignore
      this.modalService[method]({
        nzMask: false,
        nzTitle: `Test ${method} title`,
        nzContent: `Test content: <b>${method}</b>`,
        nzStyle: { position: 'absolute', top: `${pos * 70}px`, left: `${pos++ * 300}px` }
      })
    );

    this.htmlModalVisible = true;

    this.modalService.afterAllClose.subscribe(() => console.log('afterAllClose emitted!'));

    setTimeout(() => this.modalService.closeAll(), 2000);
  }
}

@Component({
  selector: 'nz-modal-custom-component',
  template: `
    <div>
      <h2>{{ title }}</h2>
      <h4>{{ subtitle }}</h4>
      <p>
        <span>Get Modal instance in component</span>
        <button nz-button [nzType]="'primary'" (click)="destroyModal()">destroy modal in the component</button>
      </p>
    </div>
  `
})
export class NzModalCustomComponent {
  @Input() title: string;
  @Input() subtitle: string;

  constructor(private modal: NzModalRef) {}

  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }
}

API#

Import this Component Individually#

You can get more detail here.

import { NzModalModule } from 'ng-zorro-antd';

NzModalService#

The dialog is currently divided into 2 modes, normal mode and confirm box mode (ie the Confirm dialog, which is called by calling confirm/info/success/error/warning). The degree of API support for the two modes is slightly different.

PropertyDescriptionTypeDefault
nzAfterOpenSpecify a EventEmitter that will be emitted when modal openedEventEmitter-
nzAfterCloseSpecify a EventEmitter that will be emitted when modal is closed completely (Can listen for parameters passed in the close/destroy method)EventEmitter-
nzBodyStyleBody style for modal body element. Such as height, padding etc.object-
nzCancelTextText of the Cancel button. Set to null to show no cancel button (this value is invalid if the nzFooter parameter is used in normal mode)stringCancel
nzClosableWhether a close (x) button is visible on top right of the modal dialog or not. Invalid value in confirm box mode (default will be hidden)booleantrue
nzOkLoadingWhether to apply loading visual effect for OK button or notbooleanfalse
nzCancelLoadingWhether to apply loading visual effect for Cancel button or notbooleanfalse
nzOkDisabledWhether to disable Ok button or notbooleanfalse
nzCancelDisabledWhether to disable Cancel button or notbooleanfalse
nzFooterFooter content, set as footer=null when you don't need default buttons. 1. Only valid in normal mode.
2. You can customize the buttons to the maximum extent by passing a ModalButtonOptions configuration (see the case or the instructions below).
string
TemplateRef
ModalButtonOptions
OK and Cancel buttons
nzGetContainerThe mount node for ModalHTMLElement / () => HTMLElementA default container
nzKeyboardWhether support press esc to closebooleantrue
nzMaskWhether show mask or not.booleantrue
nzMaskClosableWhether to close the modal dialog when the mask (area outside the modal) is clickedbooleantrue
nzMaskStyleStyle for modal's mask element.object-
nzOkTextText of the OK button. Set to null to show no ok button (this value is invalid if the nzFooter parameter is used in normal mode)stringOK
nzOkTypeButton type of the OK button. Consistent with the type of the nz-button.stringprimary
nzStyleStyle of floating layer, typically used at least for adjusting the position.object-
nzTitleThe modal dialog's title. Leave blank to show no title. The usage of TemplateRef can refer to the casestring / TemplateRef-
nzVisibleWhether the modal dialog is visible or not. When using the <nz-modal> tag, be sure to use two-way binding, for example: [(nzVisible)]="visible".booleanfalse
nzWidthWidth of the modal dialog. When using numbers, the default unit is pxstring
number
520
nzClassNameThe class name of the modal dialogstring-
nzWrapClassNameThe class name of the container of the modal dialogstring-
nzZIndexThe z-index of the Modalnumber1000
nzOnCancelSpecify a function that will be called when a user clicks mask, close button on top right or Cancel button (If nzContent is Component, the Component instance will be put in as an argument). Note: When created with NzModalService.create, this parameter should be passed into the type of function (callback function). This function returns a promise, which is automatically closed when the execution is complete or the promise ends (return false to prevent closing)EventEmitter-
nzOnOkSpecify a EventEmitter that will be emitted when a user clicks the OK button (If nzContent is Component, the Component instance will be put in as an argument). Note: When created with NzModalService.create, this parameter should be passed into the type of function (callback function). This function returns a promise, which is automatically closed when the execution is complete or the promise ends (return false to prevent closing)EventEmitter-
nzContentContentstring / TemplateRef / Component / ng-content-
nzComponentParamsWhen nzContent is a Component, the attributes in this parameter will be passed to the nzContent instanceobject-
nzIconTypeIcon type of the Icon component. Only valid in confirm box modestringquestion-circle

Attentions#

The default state of <nz-modal> will not be automatically cleared. If you wish to open new content each time, use the NzModalService service to create modals (when created as a service, the nzAfterClose event will be listened by default aim to destroy the modal).

Modals created through the NzModalService service need you to manage their own life cycle. For example, when you switch the page route, the modal box created by service will not be destroyed automatically. You need to use the modal box's reference to manually destroy it (NzModalRef.close() or NzModalRef.destroy()).

Using service to create Normal Mode modal#

You can call NzModalService.create(options) to dynamically create normal mode modals, where options is an object that supports the support given in the API above normal mode parameters

Confirm box mode - NzModalService.method()#

There are five ways to display the information based on the content's nature:

  • NzModalService.info
  • NzModalService.success
  • NzModalService.error
  • NzModalService.warning
  • NzModalService.confirm

The items listed above are all functions, expecting a settings object as parameter. Consistent with the above API, some property types or initial values are different as follows:

PropertyDescriptionTypeDefault
nzOnOkSpecify a EventEmitter that will be emitted when a user clicks the OK button (If nzContent is Component, the Component instance will be put in as an argument.). This function returns a promise, which is automatically closed when the execution is complete or the promise ends (return false to prevent closing)function-
nzOnCancelSpecify a function that will be called when a user clicks mask, close button on top right or Cancel button (If nzContent is Component, the Component instance will be put in as an argument.). This function returns a promise, which is automatically closed when the execution is complete or the promise ends (return false to prevent closing)function-
nzWidthWidth of the modal dialogstring / number416
nzMaskClosableWhether to close the modal dialog when the mask (area outside the modal) is clickedbooleanfalse

All the NzModalService.methods will return a reference, and then we can close the popup by the reference.

constructor(modal: NzModalService) {
  const ref: NzModalRef = modal.info();
  ref.close(); // Or ref.destroy(); This dialog will be destroyed directly
}

Other Methods/Attributes for NzModalService#

Methods/AttributesDescriptionType
openModalsAll currently open Modal listNzModalRef[]
afterAllCloseCallback called after all Modals closed completelyObservable<void>
closeAll()Close all modalsfunction

NzModalRef#

NzModalRef object is used to control dialogs and communicate with inside content

The dialog created by the service method NzModalService.xxx() will return a NzModalRef object that is used to manipulate the dialog (this object can also be obtained by dependency injection NzModalRef if nzContent is used as Component) , This object has the following methods:

MethodDescription
afterOpenSame as nzAfterOpen but of type Observable<void>
afterCloseSame as nzAfterClose, but of type Observable<result:any>
open()Open (display) dialog box. Calling this function will fail if the dialog is already destroyed
close()Close (hide) the dialog. Note: When used for a dialog created as a service, this method will destroy the dialog directly (as with the destroy method)
destroy()Destroy the dialog. Note: Used only for dialogs created by the service (non-service created dialogs, this method only hides the dialog)
getContentComponent()Gets the Component instance in the contents of the dialog for nzContent. Note: When the dialog is not initialized (ngOnInit is not executed), this function will return undefined
triggerOk()Manually trigger nzOnOk
triggerCancel()Manually trigger nzOnCancel

Global Configuration#

Global Configuration(NZ_MODAL_CONFIG)

if your want to set global configuration, you can use the value of provide NZ_MODAL_CONFIG to accomplish it. (eg, add { provide: NZ_MODAL_CONFIG, useValue: { nzMask: false }} to providers of your module, you can import NZ_MODAL_CONFIG from ng-zorro-antd)

The weight of global configuration, component default value, component input value:

component input value > global configuration > component default value

supported global configuration item

{
    provide: NZ_MODAL_CONFIG,
    useValue: {
        nzMask?: boolean; // Whether show mask or not.
        nzMaskClosable?: boolean; // Whether to close the modal dialog when the mask (area outside the modal) is clicked
    }
}

Note: global configuration does not have default value which component has it.

ModalButtonOptions (used to customize the bottom button)#

An array of ModalButtonOptions type can be passed to nzFooter for custom bottom buttons.

The button configuration items are as follows (along with the button component):

nzFooter: [{
  label: string; // Button text
  type?: string; // Types
  shape?: string; // Shape
  ghost?: boolean; // Whether ghost
  size?: string; // Size
  autoLoading?: boolean; // The default is true. If true, this button will automatically be set to the loading state when onClick returns a promise.

  // Tip: The `this` of below methods points to the configuration object itself. When nzContent is a component class, the contentComponentInstance parameter passed in by the method below is an instance of the component class
  // Whether to show this button
  show?: boolean | ((this: ModalButtonOptions, contentComponentInstance?: object) => boolean);
  // Whether to display loading
  loading?: boolean | ((this: ModalButtonOptions, contentComponentInstance?: object) => boolean);
  // Is it disabled
  disabled?: boolean | ((this: ModalButtonOptions, contentComponentInstance?: object) => boolean);
  // Callback of clicking
  onClick?(this: ModalButtonOptions, contentComponentInstance?: object): void | Promise&lt;void&gt; | any;
}]

The above configuration items can also be changed in real-time to trigger the button behavior change.