Reputation: 287
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
Upvotes: 11
Views: 14121
Reputation: 3671
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
}
}
import { MatDialogRef } from '@angular/material/dialog';
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>) {}
someAction() {
this.dialogRef.close();
}
}
Upvotes: 18
Reputation: 10862
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>
Upvotes: 0
Reputation: 4208
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;
Upvotes: -2