The modal popup will be triggered by various button clicks, each displaying slightly different data within the popup

As a newcomer to Angular 4, I have encountered an interesting challenge. Currently, my code consists of two separate components for two different modals triggered by two different button clicks (Add User and Edit User). However, I now face the requirement of creating a single modal popup that can be used for both scenarios (clicking 'Add User' or 'Edit User'). The fields in both modals are identical, with the only difference being that the Edit User modal is pre-populated with user data while the Add User modal displays empty fields. Any assistance on how to achieve this would be greatly appreciated. :)

Answer №1

Check out this example on StackBlitz that demonstrates how to use the Angular Material Dialog Component to show different modals based on the button clicked.
The key concept here is to pass data to the modal and customize its content accordingly.
In this instance, a simple string - either add or edit - is passed.

Main Component

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
        });
    }
}

Modal Component

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) { }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for dynamically implementing a pipe in Angular 5

In my Angular application, I have implemented a filter using a pipe to search for option values based on user input. This filter is applied at the field level within a dynamically generated form constructed using an ngFor loop and populated with data from ...

Steps for displaying a 404 page on a server-side rendered dynamic route following a client-side page transition

I'm currently developing a next.js project using Contentful as the Content Management System. My goal is to display a 404 page for a server-side rendered dynamic route after a client-side page transition. When I directly request the page (by entering ...

Global Inertia Headers

How can I ensure that a custom header (Accept-Content-Language) is sent with every request, including Inertia manual visits? Below is the code snippet where I define and set the header: import axios from 'axios'; const lang = localStorage.getIt ...

A specialized <T> interface, now enhanced with additional functionalities

Looking to create a generic type (with parameter T) that exhibits the following behavior: If K represents a key of T, allow the value type to be either T[K] | ((params?: Partial<T>) => string) If K is not a key of T, allow the value type to be ( ...

Can TypeScript Implement a Dictionary Feature Similar to C#?

Looking for guidance on how to use TypeScript interface to define these C# models: public class PageModel { public long Id { get; set; } public string Name { get; set; } public IDictionary<string, FieldModel> Fields { get; set; } } pu ...

Tips for creating a dynamic interface in TypeScript to eliminate repetitive code

Currently, I am utilizing typescript alongside the react-navigation library within my react-native project. Following the guidelines provided in the official documentation, I have been annotating my screens. One issue I have encountered is the repetitive ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

Factory function in Angular for translating using arrow syntax

When I include TranslateModule using the following code: TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }) where export function HttpLoaderFactory(http: H ...

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...

Exploring Angular: How to Access HTTP Headers and Form Data from POST Request

I am currently working with an authentication system that operates as follows: Users are directed to a third-party login page Users input their credentials The website then redirects the user back to my site, including an auth token in a POST request. Is ...

Leveraging getStaticProps in Next.js

I am currently embarking on my inaugural Nextjs project, focused on developing a basic blog utilizing the JSON placeholder API. Strangely, I am encountering an issue where the prop "posts" is being perceived as undefined. Can anyone provide assistance with ...

Anticipating the completion of post requests

I am currently working on implementing a file upload feature in Angular. I have tackled the issue of file size restrictions by creating an API endpoint that can receive file chunks. Once all the chunks are received, another endpoint needs to be triggered ...

Is there a way to deactivate a tab when it's active and reactivate it upon clicking another tab in Angular?

<a class="nav-link" routerLink="/books" routerLinkActive="active (click)="bookTabIsClicked()" > Books </a> I am currently teaching myself Angular. I need help with disabling this tab when it is active ...

Extending momentjs functionality with a custom method in Typescript

I am attempting to extend the momentjs prototype with a new function. In JavaScript, I achieved this with the following code: Object.getPrototypeOf(moment()).isWeekend = function() { return this.isoWeekday() >= 6; }; How can I accomplish this in T ...

Retrieve the part of a displayed element

Presently, I am developing a modal system using React. A button is located in the sidebar and the modal is represented as a div within the body. In the render function of the main component of my application, two components are being rendered: MyModal M ...

Enhancing NG Style in Angular 6 using a custom function

Today, my curiosity lies in the NG Style with Angular 6. Specifically, I am seeking guidance on how to dynamically update [ngStyle] when utilizing a function to determine the value. To better illustrate my query, let me present a simplified scenario: I ha ...

Using Angular's async, you can retrieve a value returned by a promise

Within the library I am currently utilizing, there is a method called getToken which can be seen in the following example: getApplicationToken() { window.FirebasePlugin.getToken(function(token) { console.log('Received FCM token: ' + to ...

Iterate and combine a list of HTTP observables using Typescript

I have a collection of properties that need to be included in a larger mergeMap operation. this.customFeedsService.postNewSocialMediaFeed(this.newFeed) .mergeMap( newFeed => this.customFeedsService.postFeedProperties( newFeed.Id, this.feedP ...

Is there a method to automatically eliminate all unnecessary properties in an Angular project?

In my extensive Angular project, I suspect that there are numerous declared properties in .component.ts that are not being used. Is there a method available to automatically eliminate all unused properties within an Angular project while also taking into ...

The error message for Angular FormControl's minimum length validation is not showing up in the errors

My goal is to access the minlength error, but when I check all the errors, it's not there. Below is my form control title: new FormControl("", [Validators.minLength(10), Validators.required]), I expect to see both the required and minlengt ...