Demonstrating a feature in a custom Angular Material dialog box

I have a reusable custom Material UI Dialog that I want to utilize to show different components. For instance, I would like to display a Login component on one occasion and a Registration component on another. However, the issue arises when I assign my component to the body of the dialog - it displays the code of my component instead of rendering it as intended. While sending text works fine, sending a component to be displayed in the middle of the Dialog seems to be impossible. How can someone pass a component as an object or template to be shown in a dialog? The Invitation component consists of HTML code, input controls, and a button, and I aim to showcase it in the center of my dialog, similar to a page displayed within an iframe. Any insights or assistance on this matter would be greatly appreciated.


    <div class="title">
        <h2 mat-dialog-title>{{ data.title }}</h2>
        <span mat-dialog-close class="material-icons closeButton">close</span>
    </div>
    <hr>
    <div>
        <mat-dialog-content class="mat-typography">
            {{ data.body }}
        </mat-dialog-content>
        <hr>
        <div class="actionSection">
            <mat-dialog-actions>
                <button mat-button class="secondary" mat-dialog-close>{{ data.cancelButton }}</button>
            </mat-dialog-actions>
        </div>
    </div>
</div>

my calling code is:
const dialogRef = this.dialogService.open(CustomDialogComponent,
      {
        hasBackdrop: true,
        disableClose:true,
        data:{
          title: 'Invite User',
          body: InvitationComponent,
          cancelButton: 'Close' }

This is how my CustomDialogComponent appears:


export class CustomDialogComponent implements OnInit {

  constructor(@Inject(MAT_DIALOG_DATA) public data: any,
    private dialogRef: MatDialogRef<CustomDialogComponent>) {
    console.log(data.body);
  }

  ngOnInit() {
  }

Answer №1

If you want to display different contents in a dialog component, simply create two templates in the HTML file and switch between them based on the scenario. For a clearer explanation, check out this StackBlitz example I prepared: https://stackblitz.com/edit/angular-mat-dialog-kfdktu

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

Building a TypeScript Rest API with efficient routing, controllers, and classes for seamless management

I have been working on transitioning a Node project to TypeScript using Express and CoreModel. In my original setup, the structure looked like this: to manage users accountRouter <- accountController <- User (Class) <- CoreModel (parent Class o ...

"Error: Authentication failed in JWT authentication using Node.js/Express due to

I'm encountering an issue with Jwt, specifically the "Invalid Signature" error. After a user logs in, I generate a token using jsonwebtoken: userSchema.methods.generateJwt = function() { var expiry = new Date(); //expiry.setDate(expiry.getDate() ...

Next.js production build encountering an infinite loading error

I have been utilizing the Next.js TypeScript starter from https://github.com/jpedroschmitz/typescript-nextjs-starter for my current project. The issue I am facing is that when I attempt to build the project after creating numerous components and files, it ...

Error in Angular nested form: Unable to access property 'length' of null object

I have created a nested form with various form controls: this.newRequest = this._fb.group({ requestType: [], tripType: [], feeders: [''], directFlight: [], departure: [''], arrival: [''], depDate: ...

Exploring the use of MockBackend to test a function that subsequently invokes the .map method

I've been working on writing unit tests for my service that deals with making Http requests. The service I have returns a Http.get() request followed by a .map() function. However, I'm facing issues with getting my mocked backend to respond in a ...

What is the most effective way to code and define a MatSelect's MatSelectTrigger using programming techniques?

How can I programmatically set the MatSelectTrigger template for a MatSelect instance using the provided reference? The documentation mentions a settable customTrigger property, but information on the MatSelectTrigger class or how to create one dynamically ...

The PrimeNg p-calendar is showing an incorrect month for the selected date

Utilizing the p-calendar component from primeNg has resulted in a discrepancy when comparing or checking dates, specifically returning an incorrect month. <p-calendar [locale]="nl" [inline]="true" [showOtherMonths]=" ...

The axios GET request failed to return a defined value

My current issue involves making a get request using the following code snippet: router.get('/marketUpdates',((request, response) => { console.log("market updates"); var data: Order[] axios.get('http://localhost:8082/marketUpdates& ...

Is node.js necessary for running TypeScript?

Node.js is necessary for installing TypeScript. I believe that TypeScript utilizes Node.js to compile .ts files into .js files. My concern is whether the generated .js file needs node.js in order to function properly. From what I've observed, it seem ...

Convert a Java library to JavaScript using JSweet and integrate it into an Angular project

Just recently, I embarked on my journey to learn TypeScript. To challenge my newfound knowledge, I was tasked with transpiling a Java library using JSweet in order to integrate it into an Angular project. This specific Java library is self-contained, consi ...

I encountered an issue with the proxy configuration while working with Npm and Angular, specifically after installing and then uninstalling

Ever since I removed Fiddler, I've been encountering issues with using Angular and npm, specifically related to proxy errors. When attempting an http call with Angular, I receive the following error: [HPM] Error occurred while trying to proxy reque ...

Checking radios or checkboxes will always result in a null value when retrieving their form values

After following the instructions in the Angular 2 cookbook for dynamic forms, I encountered an issue with the radios and checkboxes. Despite checking them, they always return a null value. Interestingly, the touched properties of the radios and checkboxes ...

Creating Instances of Parameterized Types

Consider the following scenario: class Datum {} An error message (error TS2304: Cannot find name 'T') is encountered when attempting the following: class Data<T extends Datum> { datum: T constructor() { this.datum = new ...

Transforming a string such as "202309101010" into a date entity

Need to convert a string in the format "YYYYMMDDHHMM" (e.g. "202309101010") into a Date object in TypeScript? Check out this code snippet for converting the string: const dateString: string = "202309101010"; const year: number = parseInt(dateString.subst ...

Utilize Angular 2 with Google Maps Places Autocomplete to dynamically update an input field with location suggestions [DOM manipulation]

Recently, I have been utilizing the "Angular 2 + Google Maps Places Autocomplete" search functionality. Essentially, it involves an input field that looks like this: <input placeholder="search your location" autocorrect="off" autocapitalize="off" spell ...

Move the page to the beginning of the vertical stepper upon clicking the "next" button

I am currently working on optimizing a lengthy form to enhance user experience. To illustrate my point, I have come across a simplified example of the code I am dealing with which can be found here. My primary goal is to ensure that when a user proceeds t ...

Using Checkbox from material-UI to add and remove strikethrough on a to-do list task

const Todo: React.FC<ITodoProps> = (props) => { const [textInput, setTextInput] = useState(''); const { addTodo, userId, todosForUser, user, } = props; if (user == null) { return ( <Grid container={true} direction=&apo ...

The test case for creating a component in Jasmine titled "should create" threw an error and failed with a TypeError stating: "FAILED TypeError: Cannot read property 'next' of undefined"

One of the key components in my application is responsible for fetching data from the store. @Component({ selector: 'iomt-user', templateUrl: './user.component.html', styleUrls: ['./user.component.scss'] }) export class ...

Integrating Constant Contact API into a Next.js application

I'm trying to integrate the Constant Contact API into my Next.js application. I've looked through the documentation, but it only provides examples for PHP and Java. How can I effectively use the authentication flow and create an app on the dashbo ...

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...