How to return the changes or return the value to parent after modal close in angular

Viewed 398

Here's the code:

parent.ts

newInputName = '';
  inputName = '';
  addName = false;

constructor() {
private modal: NzModalService) { }

ngOnInit() {

    this.modal.afterAllClose.subscribe(md => {
      console.log(this.addArea)
    });
  }
 addItem(): void {
    this.inputName = this.name;
    this.newInputName = '';
    this.addName = true;
  }

parent.html

 <div class="modal-body">
        <label class="pb-2">Name</label>
        <input nz-input class="mr-2" [(ngModel)]="newInputName" placeholder="Type name...">
      </div>
    
      <nz-divider></nz-divider>
      <section class="form-footer" nz-row>
        <div nz-col>
          <button class="mr-1" nz-button nzType="primary" type="button" (click)="addItem()"
            [disabled]="newInputName.length <= 0">Add Name</button>
          <button nz-button class="btn-secondary" type="button" (click)="modalRef.close()"
            [textContent]="'Cancel' | translate"></button>
        </div>
      </section>

child.ts

  @Input() addName: boolean;
    editLayout(shopFloor?: any, lines?: any) {
    this.modalRef = this.modal.create({
      ......
    .....
    .....
    .......
    .......
    });

    this.modal.afterAllClose.subscribe((x: any) => {
      this.addName = false;
    });
  }

What I'm trying to do here is after submitted, the modal will be closed then the value addArea will be changed to false if the value of addName is true.

cause I'm having trouble when I try to save/submit the value still true when I try to change the value of addArea to true.

I also tried to do like this:

parent.html

<app-child [addNewName]="addName"></app-child>

child.ts

 @Input() addName: boolean;
 @Output()
  addNameChange = new EventEmitter<boolean>();

 @Input() addName: boolean;
        editLayout(shopFloor?: any, lines?: any) {
        this.modalRef = this.modal.create({
          ......
        .....
        .....
        .......
        .......
        });
    
        this.modal.afterAllClose.subscribe((x: any) => {
          this.addNameChange.emit(!this.addName);
        });
      }

But still it doesn't work.

1 Answers

You were almost there, on top of what you already tried (adding event emitter and emitting when the modal is done and ready to tell the parent component what to do), you also have to tell the parent component to do something when the child emits, adding the following to your parent html template:

<app-child [addNewName]="addName" (addNameChange)="resetNameChange($event)"></app-child>

and then in your parent .ts file:

...
resetNameChange(val) {
  ...do logic here, probably this.addName = val;
}
Related