Search code examples
angularmodal-dialogreset

Angular material dialog form is not resetting after submit


I have a requirement in which i have a model popup in the header navigation. I am using angular material dialog for the popup model. Model popup is working fine only one issue i am facing currently. If i close the model and re open it, the form values are not resetting.

header.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatDialogConfig } from '@angular/material/dialog';
import { ModelComponent } from '../model/model.component';
import { Subscription } from 'rxjs';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  @ViewChild('modelForm', {static: false}) modelForm: NgForm;

  firstName: string = '';
  lastName: string = '';
  dialogConfig: MatDialogConfig;
  dialogWithForm: MatDialogRef<ModelComponent>;
  routeQueryParams$: Subscription;

  constructor( private router: Router, public dialog: MatDialog, private route: ActivatedRoute,) { 
    this.routeQueryParams$ = route.queryParams.subscribe(params => {
      if (params['dialog']) {
        // this.openDialog();
        this.showDialog();
      }
    });
  }

  ngOnInit(): void {
    // this.modelForm.resetForm();
    }
  
  showDialog(){
    // Opening the dialog component
    const dialogWithForm = this.dialog.open(ModelComponent, {
      width: '40%',
      // height: '400px',
      data: { firstName: this.firstName, lastName: this.lastName }
      });

    // When user close the dialog
    dialogWithForm.afterClosed().subscribe(result => {
      console.log('You have closed the dialog');
      if (result) {
        // this.modelForm.resetForm();
        this.router.navigate(['/test'], { relativeTo: this.route });
        // this.modelForm.resetForm();
        // this.modelForm.reset();
      }
        // this.modelForm.resetForm();
        // this.dialogWithForm.close([]);
        // this.dialogWithForm.close(this.modelForm.value);
        this.dialogWithForm.close();

    });
    // this.modelForm.reset();

  }
  
  ngOnDestroy() {
    this.routeQueryParams$.unsubscribe();
  }
}

model.component.ts

import { Component, OnInit, Inject, ViewChild } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { NgForm } from '@angular/forms';

export interface DialogData {
  firstName: string;
  lastName: string;
 }

@Component({
  selector: 'app-model',
  templateUrl: './model.component.html',
  styleUrls: ['./model.component.css']
})
export class ModelComponent implements OnInit {
  @ViewChild('modelForm', {static: false}) modelForm: NgForm;
  firstName: string = '';
  lastName: string = '';

  constructor(private router: Router, public dialogRef: MatDialogRef<ModelComponent>, @Inject(MAT_DIALOG_DATA) public data: DialogData) { }

  ngOnInit(): void {
    // this.modelForm.reset();
  }
  onNoClick(): void {
    this.dialogRef.close();
    this.router.navigateByUrl('/contact');
  }

}
header.component.html


                <a class="nav-link" routerLinkActive="active"  routerLink="/queries" [queryParams]="{dialog: true}">Connections</a>
     


model.component.html
 
 <form #modelForm="ngForm" id="modelForm" (ngSubmit)="onSend(modelForm)"> 
<div class="header">  
    <h2 mat-dialog-title>Create Modekl</h2>
</div>
<div mat-dialog-content>
    <mat-form-field>
    <input placeholder="First Name" matInput [(ngModel)]="data.firstName" name="firstName" required>
    </mat-form-field><br>
    <mat-form-field>
    <input placeholder="Last Name" matInput [(ngModel)]="data.lastName" name="lastName" required>
    </mat-form-field><br>
</div>
<div mat-dialog-actions>
    <button mat-button (click)="onNoClick()" class="btn btn-primary run-button">Cancel</button>
    <button mat-button [mat-dialog-close]="data" class="btn btn-primary run-button" [disabled]="modelForm.invalid">Create</button>
</div>
</form>

I tried resetting the form in ngOnInit and afterClosed(). But its not working. Can anyone let me know where I am going wrong here? Thanks.


Solution

  • You're binding the data to the input fields and not to the form, so you have to reset these values. If you want the dialog to be "empty" when you display it, you can reset the values before opening it, like that:

      showDialog(){
        this.firstName = "";
        this.lastName = "";
        // Opening the dialog component
        const dialogWithForm = this.dialog.open(ModelComponent, {
          ...