10

I have a md-dialog component - DialogComponent - which i open from sibling component - SiblingComponent - and i want to close it in dialog.component.ts after some actions.

DialogComponent basically is a form with submit button, submitting form takes me to dialog.component.ts function where i'm doing some validation and sending data to service.

After validation passes and data is sent i want to make some timeout and then automatically close dial window, but i dont know how to run something like md-dialog-close in dialog.component.ts

Nehal
  • 13,130
  • 4
  • 43
  • 59
esquarial
  • 277
  • 1
  • 4
  • 15

3 Answers3

16

You can inject an MdDialogRef into the dialog component class, and use that to close it. Example:

export class DialogComponent {

    constructor(private dialogRef: MdDialogRef<DialogComponent >) { }

    someAction() {
        // do your thing here
        this.dialogRef.close(); // <- this closes the dialog. 
        // You can also wrap it in setTimeout() if you want
    }
}
Amirhossein Mehrvarzi
  • 18,024
  • 7
  • 45
  • 70
Andrei Matracaru
  • 3,511
  • 1
  • 25
  • 29
0

I arrived here looking for a similar situation but for MatDialog

My scenario is that I had a MatDialog that contains and EditParkingDialogComponent that contains a ParkingFormComponent, why so complicated ? because I am reusing the ParkingFormComponent to be used as a form or into a dialog.

What I needed was to close the main MatDialog when a Parkin was updated in the ParkingFormComponent, example when the data was saved.

Here is what I did:

In the ParkingFormComponent.component.ts I emit an event when the parking is updated

  @Output()
  parkingUpdated: EventEmitter<any> = new EventEmitter<any>();

  updateParking() {
    .....
    this.parkingUpdated.emit();
  }

In the EditParkingDialogComponent.component.ts (intermediate component)

  constructor(private dialogRef: MatDialog) { }

  onParkingUpdated() {
      this.dialogRef.closeAll();
  }

In the EditParkingDialogComponent.component.html

<app-parking-form [mode]="formMode" [parkingModel]="currentParking" (parkingUpdated)="onParkingUpdated()"></app-parking-form>
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
-2

You need to get a reference to the component you want to access by using @ViewChild(MyComponent) myComponent; in the parent.

From 1 sibling you need to emit an event to the parent by using @Output() event = new EventEmitter(); and then in the parent you can access the other sibling by using it's reference.

(you don't need an @Output(), you can also create two references in the parent @ViewChild(SiblingOneComponent) & @ViewChild(SiblingTwoComponent) and a variable in the child component: parentComponent: ParentComponent. and set it (in the parent) by using SiblingOneComponent.parentComponent = this;

Carsten
  • 4,005
  • 21
  • 28