angularng-zorro-antd

NgZorro Modal - How to pass data into the modal in Angular 16?


I'm using Ant Design for Angular library ng-zorro-antd.

This was working on Angular 12, but now after upgrading to Angular 16, I'm seeing this error: ERROR TypeError: Cannot read properties of undefined (reading 'name')

I create the modal like this:

 private _createDeleteModal(vehicleGroupDetails: VehicleGroupDetails) {
    this.modalService
      .create({
        nzTitle: 'Delete Vehicle Group',
        nzContent: VehicleGroupDeleteComponent,
        nzComponentParams: { existingVehicleGroup: vehicleGroupDetails },
      })

And in the modal component I would get the params data like this:


export class VehicleGroupDeleteComponent implements OnInit {
  @Input() existingVehicleGroup: VehicleGroupDetails;
  ...
  this.vehicleGroupForm = new FormGroup({
    name: new FormControl(this.existingVehicleGroup?.name ?? '', [
      Validators.required,...

But now it seems the data isn't there at all and I just see the above error repeating over and over, crashing the browser.


Solution

  • Use nzData and NZ_MODAL_DATA in Angular v16 and higher

    Things changed with the upgrades to v16+ for both Angular and Ng-Zorro.

    Ng-Zorro deprecated nzComponentParams in favor of nzData. It also switched to an injectable data sharing model. So if you're seeing this issue in v16 or higher, you'll need to switch to nzData and the injectable NZ_MODAL_DATA.

    The following should work for you.

    In the place you create the modal, only one change is needed: use nzData instead of nzComponentParams

     private _createDeleteModal(vehicleGroupDetails: VehicleGroupDetails) {
        this.modalService
          .create({
            nzTitle: 'Delete Vehicle Group',
            nzContent: VehicleGroupDeleteComponent,
            nzData: { existingVehicleGroup: vehicleGroupDetails },
          })
    

    You'll need a few more changes in the modal component:

    import { Component, inject, OnInit } from '@angular/core';
    import { NzModalRef, NZ_MODAL_DATA } from 'ng-zorro-antd/modal';
    export class VehicleGroupDeleteComponent implements OnInit {
      readonly nzModalData = inject(NZ_MODAL_DATA);
      existingVehicleGroup: VehicleGroupDetails;
    
      ngOnInit(): void {
        this.existingVehicleGroup = this.nzModalData.existingVehicleGroup;
      }
    }
    
    

    That should enable the rest of the code in your modal component to work as is.

    More here: Modal

    And in this explanation of the changes: Github