Reputation: 85
Being new to Angular 4 I came across with an issue. In my code currently I have 2 separate components for 2 different modals in my code for 2 different button clicks (Add User and Edit User). Now I have a requirement where I have to come up with a single modal popup that fires in both the cases (i.e. on click of 'Add User' as well as 'Edit User'). All the fields in both the modals are same except that the Edit User modal is already populated with user data while Add User modal shows empty fields. Any help regarding this is highly appreciated. :)
Upvotes: 1
Views: 2709
Reputation: 4650
Here is a simple stackblitz example using Angular Material Dialog Component to display a different modal depending on which button was clicked.
The main principle consists in passing data to your modal and adapt its content to what was passed.
In this example, I simply pass a string: add
or edit
.
import { Component, Inject } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DialogComponent } from './dialog.component';
@Component({
selector: 'my-app',
template: `
<button (click)="openDialog('add')">add</button>
<button (click)="openDialog('edit')">edit</button>
`
})
export class AppComponent {
constructor(public dialog: MatDialog) { }
openDialog(action) {
this.dialog.open(DialogComponent, {
data: action
});
}
}
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
template: `
<h4>action = {{action}}</h4>
<p *ngIf="action === 'add'">add content displayed</p>
<p *ngIf="action === 'edit'">edit content displayed</p>
`,
})
export class DialogComponent {
constructor(@Inject(MAT_DIALOG_DATA) public action: string) { }
}
Upvotes: 2