For an unknown cause, the Angular dialog box is not showing up

I've been struggling to implement a dialog window in my project, but for some reason, it's not working as expected. Rather than opening the dialog window, the content of the dialog component is being added at the bottom of the page like an HTML element without dimming the rest of the page. I'm just trying to create a simple dialog window and have followed similar examples on YouTube and official documents. I've checked the code multiple times but can't seem to find the mistake. Am I overlooking something?

Here is the code for the Dialog component:

import { Component, OnInit } from '@angular/core';

@Component({
     selector: 'app-dialog',
     templateUrl: './dialog.component.html',
     styleUrls: ['./dialog.component.scss']
})
export class DialogComponent implements OnInit {

     constructor() { }


     ngOnInit() {
     }

}

Dialog HTML:

<p>
     dialog works!
</p>

And here is the Main page component:

import { Component } from '@angular/core';
import { MatDialog } from '@angular/material';
import { DialogComponent } from './Components/dialog/dialog.component';

@Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.scss']
})
export class AppComponent {

     constructor(public dialog: MatDialog) {
          this.openDialog();
     }

     openDialog() {
          const dialogRef = this.dialog.open(DialogComponent, {
               width: '500px',
               height: '1080px'
          });

          dialogRef.afterClosed().subscribe(result => {
               console.log(`Dialog result: ${result}`);
          });
     }
}

Also, don't forget to check the app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DialogComponent } from './Components/dialog/dialog.component';
import { MatDialogModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
     declarations: [
          AppComponent,
          DialogComponent,
     ],
     imports: [
          BrowserModule,
          AppRoutingModule,
          FormsModule,
          MatDialogModule,
          BrowserAnimationsModule,
     ],
     providers: [],
     bootstrap: [AppComponent],
     entryComponents: [
          DialogComponent
     ],
})
export class AppModule { }

Answer №1

It is essential to have all the necessary components in place for it to function properly. Otherwise, it may not work as expected:) http://material.angular.io/guide/getting-started

You seem to be missing the MatDialogRef in the constructor of your dialog.

import { MatDialogRef } from '@angular/material';

constructor(public dialogRef: MatDialogRef<DialogComponent>) {
}

Main page component:

Trying to call it like this is not feasible (as the UI is not ready at that point):

constructor(public dialog: MatDialog) {
      this.openDialog();
 }

Instead, it should be called within ngOnInit method (or ngAfterViewInit).

import { OnInit } from '@angular/core';

export class AppComponent implements OnInit {

    ...

    ngOnInit() {
        this.openDialog();
    }

    ...
}

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

Steps for adjusting the matMenuTriggerFor area so it only triggers when hovering over the arrow

Hello there! I'm currently working on adjusting the trigger area for opening the next menu panel. Right now, the next menu panel opens whenever I hover over either the title or the arrow. However, my goal is to have the menu open only when I hover ove ...

What is the process for removing items from Firebase Storage utilizing Angularfire2?

Hello, I am new to using Angularfire2 and I am facing an issue with deleting a folder from Firebase Storage when a user presses the delete button. I have searched through the Angularfire2 documentation but couldn't find any information on how to achie ...

How to safely add multiple objects to an array in TypeScript & React without replacing existing objects - Creating a Favorites list

I'm in the final stages of developing a weather application using TypeScipt and React. The last feature I need to implement is the ability for users to add queried locations to a favorites list, accessed through the "favorites" page. By clicking on a ...

Strategies for Implementing Pagination in an Angular 2 HTML Table Without the Use of Third-Party Tools

I have an HTML table that displays basic details along with images. I am looking to implement pagination for this table in Angular 2. Are there any alternatives to using ng2-pagination? ...

NGXS - how parent state can access child state

I am working with parent-child states: @State({ name: 'parent', default: { parentProp : 'foo' }, children: [ ChildState, ] }) class ParentState {} Additionally, I have: @State({ name: 'child&apos ...

Navigating the Relationship Between Strings and Objects in Angular

I am looking for a way to create a mapping from a string to an object in Angular, similar to how it is done in JAVA. Here is an example of the json String I have: {"policyNumber":"1234", "firstName":"archi"} The TypeScript Object looks like this: export ...

Angularfire2 throws an error with the message, "app/bad-app-name," when using Firebase

Encountering an error in my Angular app where Firebase is returning a code bad-app-name. The app utilizes angularfire2 within the Angular framework. After verifying the Firebase configuration and confirming it is correct, how can this error be resolved? ...

Learn how to store the data from a FormArray into a MySQL database using Node.js

I am facing an issue and need assistance. Apologies for my limited English proficiency, but I will do my best to articulate the problem in hopes that you can assist me. Thank you. I am developing an activity management platform where employees log in ...

Ordering in the template is a breeze

Within my template, I want to display the available hours in order. Here is an example of my template: <ul> <li class="heure" *ngFor="let heure of plageHeure" [ngClass]="{ odd: (heure%2 == 0), even: heure %2 == 1 } "> <a *ngIf ...

Creating a TypeScript map with conditional items

I encountered an error while trying to add an item conditionally to a Map using .filter, receiving the message Type 'null' is not assignable to type 'readonly [string, Book]'.(2769). This issue seems to arise only when adding items cond ...

Is there a way for me to manually manipulate the advancement of the progress bar from @ngx-progressbar/core in Angular5/Ionic4?

I've been working on implementing a progress bar into my application using the @ngx-progressbar/core library. However, I'm facing an issue where I can't seem to control its progress effectively. Whenever I try to increase the progress increm ...

Ways to retrieve the value of each parent element within a nested array of objects

I have a complex array of objects where each object may contain nested children. For example: const data = [ { id: 1, name: 'parent 1', children: [ { id: 'c1', nam ...

Display the first item last in an *ngFor loop in Nativescript Angular

I'm facing some confusion with the sorting of an array in JavaScript. Although the index, last, and first seem to be correct, the result is not as expected. Versions @angular/core: 4.1.0 nativescript-angular: 3.1.3 typescript: 2.4.0 Expected 1234 ...

ValueError: The object is not a valid HTMLInputElement in Angular 5

I'm attempting to implement autocomplete functionality for an address using the Google Maps API in my application, but I keep encountering the "InvalidValueError: not an instance of HTMLInputElement" error. Here are the approaches I have experimented ...

Error: Unable to locate ng command when attempting to set up a new project with angular-cli

After installing angular-cli globally with the command npm install -g angular-cli, I encountered an error when attempting to create a new project using ng new my-project: Error: ng command not found ...

Angular 9: How to Return an Object Instead of a Boolean with an Observable Getter in BehaviorSubject

Apologies if this question has already been addressed on Stack Overflow, but I haven't found a suitable solution yet. I am working with a BehaviorSubject that tracks a boolean state. I have a public getter method that returns an Observable of the Beh ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

Issue with visibility of delete and edit icons in ng-repeat when clicking outside of the element

Within an ng-repeat loop, I am displaying a list of items with both Edit and Delete icons next to each item: Item1 (Edit) (Del) Item2 (Edit) (Del) Item3 (Edit) (Del) Item4 (Edit) (Del) When the user clicks on the Edit button, I change the content editabl ...

The attribute 'getValue' is not a valid property for the data type 'Subject<boolean>'

Currently, I am working with Angular2 and have a BehaviorSubject. isOpen$: Subject<boolean> = new BehaviorSubject<boolean>(true); When I try to retrieve the latest value using: isOpen$.getValue() It functions correctly, however, there is a ...

What is the best way to transform the request query id = ' [12eetftt76237,jhgasduyas7657] ' into an array of elements or strings like [12eetftt76237,jhgasduyas7657]?

Hey there, I am working on a project using hapijs and typescript. I have a requirement to send an array of IDs as parameters through the request URL. Here is an example of the URL: localhost:3444/?id='[askjajk78686,ajshd67868]' I attempted to u ...