Display the result of a button from chlid component in parent component - Angular

Viewed 30

I have a button in the chlid component which has a form, on click of the button, it adds in DB and gives out an alert. I want to display the alert in the parent component screen which shows the list of data in DB.

HTML:

<button class="pt-primary adconfig-button" *ngIf="!isEditMode" [disabled]="!testSuccessful" (click)="storeNewConnection()">Add Configuration</button> 

TS:

        this.adService.addAdConfiguration(this.adConfigurationObj, this.isEditMode).subscribe((response) => {
            const msg: string = response.Status === ResultStatus.Success ? this.alerts.push(
                {
                    msg: 'Configuration added successfully!',
                    type: 'success',
                    timeout: 3000
                }) : response.Details;
        });
    }

        this.router.navigate(['/configuration/groups-permissions'], { state: { isAdConfig: true } });

I want to route to this path (parent component) and display the alert there.

How can accomplish it?

1 Answers
  1. The routing must be inside the subscription callback block to ensure it gets executed after the asynchronous call this.adService.addAdConfiguration() has responded.

  2. There are multiple ways to pass data using Angular Router. The following shows leveraging optional parameters.

Sender component

this.adService.addAdConfiguration(this.adConfigurationObj, this.isEditMode).subscribe((response) => {
  const msg: string = response.Status === ResultStatus.Success 
    ? this.alerts.push({
        msg: 'Configuration added successfully!',
        type: 'success',
        timeout: 3000
      }) 
    : response.Details;

    this.router.navigate(
      [
        '/configuration/groups-permissions',
        { message: JSON.stringify(msg) }
      ], 
      { state: { isAdConfig: true } }
    );
});

Recipient component

import { ActivatedRoute } from '@angular/router';

export class SomeComponent implements OnInit {
  message: any;

  constructor(private _actRoute: ActivatedRoute) { }

  ngOnInit() {
    this.message = JSON.parse(this._actRoute.snapshot.paramMap.get(message));
  }
}

Edit: Typo ActivateRoute -> ActivatedRoute

Related