How to refresh component after MatDialog close and data updated in database in Angular 6?

11,841

You're only calling getAllClients() during the OnInit lifecycle hook of ClientsComponent. This means it will only load the clients on initialisation of the component (which is why you see the new client when you navigate away and back again, as the component re-initialises and the OnInit lifecycle hook is fired again).

To counter that, you have two options (well, more than two if you were using state management (ngRx for example)).

1) When you've added your new client, and closed the dialog, immediately call getAllClients() again, by subscribing to the afterClosed event of MatDialog

this.addClientDialogRef.afterClosed().subscribe(() => { this.getAllClients(); } );

or

2) Provide the new client object via the afterClosed event from the dialog itself, and push the new object to you clients array. The only caveat being, you'll need to return the new client object from your HTTP request in saveClient

AddClientComponent

saveClient(formdata: any) {
    let theForm = this.clientForm.value;
    this.clientService.addClient(theForm).subscribe(data => {
       if (data.success === false) {
          this.toastr.error(data.message);
       } else {
          this.toastr.success(data.message);
          this.ngOnInit();
          this.dialogRef.close(data.client); // <--- Assuming the new object comes under the 'client' key of your response.
       }
       this.clientForm.reset();
    });
}

ClientsComponent

addClientDialogRef.afterClosed().subscribe((client: Client) => {
    this.clients.push(client);
}

The afterClosed event is documented (briefly) here: https://material.angular.io/components/dialog/overview

The MatDialogRef provides a handle on the opened dialog. It can be used to close the dialog and to receive notification when the dialog has been closed.

dialogRef.afterClosed().subscribe(result => {   console.log(`Dialog
   result: ${result}`); // Pizza! });

dialogRef.close('Pizza!');
Share:
11,841
sneha_h
Author by

sneha_h

Updated on June 11, 2022

Comments

  • sneha_h
    sneha_h almost 2 years

    I am learning a MEAN stack app with angular 6. Here I want to refresh the component after adding a new client/car/driver/booking or updating a new client/car/driver/booking. But after adding a new value, the component showing all the values doesn't update or refresh(not able to see the current value at that time), but when i route between component and then go back to the same component it updates and shows all the values.

    I want that as the value is added or updated from a dialog form, it gets displayed at that time.

    Here is add client component

    export class AddClientComponent implements OnInit {
    
      clientForm: FormGroup;
    
      constructor(private fb: FormBuilder,
        private clientService: ClientService,
        private toastr: ToastrService,
        private router: Router,
        public dialogRef: MatDialogRef < AddClientComponent > ) {
    
        this.clientForm = this.fb.group({
          'clientname': new FormControl(""),
          'clientphoneno': new FormControl(""),
          'clientemail': new FormControl(""),
          'clientaddress': new FormControl("")
        });
    
      }
    
      ngOnInit() {
        this.router.navigate(['/admin/clients']);
      }
    
      saveClient(formdata: any) {
        let theForm = this.clientForm.value;
        this.clientService.addClient(theForm).subscribe(data => {
          if (data.success === false) {
            this.toastr.error(data.message);
          } else {
            this.toastr.success(data.message);
            this.ngOnInit();
            this.dialogRef.close();
          }
          this.clientForm.reset();
        });
      }
    
      close() {
        this.dialogRef.close();
      }
    
    }

    here is the client component where the added values are displayed

    export class ClientsComponent implements OnInit {
    
      public currentClient: IClient;
      clients: any;
    
      addClientDialogRef: MatDialogRef < AddClientComponent > ;
      editClientDialogRef: MatDialogRef < EditClientComponent > ;
    
      constructor(public dialog: MatDialog,
        private dialogService: DialogService,
        private clientService: ClientService,
        private router: Router) {}
    
      openAddClientDialog() {
        this.dialogService.open(AddClientComponent, {
          width: '500px'
        })
      }
    
      openEditClientDialog(id) {
        this.dialogService.open(EditClientComponent, {
          width: '500px',
          data: {
            'id': id
          }
        })
      }
    
      ngOnInit() {
        this.getAllClients();
      }
    
      getAllClients() {
        this.clientService.getClients().subscribe((res) => {
          this.clients = res;
        }, err => {
          console.log(err);
        });
      }
    
      deleteClient(id) {
        this.clientService.deleteClient(id)
          .subscribe(res => {
            this.router.navigate(['./clients']);
            this.ngOnInit();
          }, (err) => {
            console.log(err);
          });
      }
    
    
    }

    here is the client service

    addClient(oClient) {
      let headers = new Headers({
        'Content-Type': 'application/json'
      });
      let options = new RequestOptions({
        headers: headers
      });
      return this._http.post('http://localhost:3000/admin/clients/add', JSON.stringify(oClient), options).pipe(
        map((response: Response) => response.json()));
    }
    
    getClients() {
      let headers = new Headers({
        'Content-Type': 'application/json'
      });
      let options = new RequestOptions({
        headers: headers
      });
      return this._http.get('http://localhost:3000/admin/clients', options).pipe(
        map((response: Response) => response.json()));
    }
    
    getClient(clientid) {
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      let options = new RequestOptions({
        headers: headers
      });
      return this._http.get(`http://localhost:3000/admin/clients/${clientid}`, options).pipe(
        map((response: Response) => response.json()));
    }
    
    editClient(clientId, oClient) {
      let headers = new Headers({
        'Content-Type': 'application/json'
      });
      let options = new RequestOptions({
        headers: headers
      });
      return this._http.put(`http://localhost:3000/admin/clients/edit/${clientId}`, JSON.stringify(oClient), options).pipe(
        map((response: Response) => response.json()));
    }

  • sneha_h
    sneha_h over 5 years
    I tried both ways but error is coming ERROR TypeError: Cannot read property 'afterClosed' of undefined