angulardialogangular-material

I can't inject MAT_DIALOG_DATA! Error: inject() must be called from an injection context


I'm using MAT_DIALOG_DATA to pass data to my dialog, however, I get this error in my browser console.

Uncaught Error: inject() must be called from an injection context
    at injectInjectorOnly (core.js:1767)
    at inject (core.js:1778)
    ...
    ...
    ...

First of all, I have to point out that I'm using angular 7.

I watch many videos and read many articles that show that what I included in my project is enough: - I imported MAT_DIALOG_DATA from angular material. - I used dialog reference. - I define my injection in the constructor.

here the component.ts codes:

import { Component, OnInit, inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';

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

  constructor(
    @inject(MAT_DIALOG_DATA) public data: any,
    public matDialogRef: MatDialogRef<TableEditorDialogComponent>
   ) { }

  ngOnInit() {
  }

  getMessageId(id : Number){
  }
}

I'm expecting to pass data to the dialog. What's is going on right now. My program Compiles successfully but inside the browser, the program stops working and show the error from the error.

Uncaught Error: inject() must be called from an injection context
    at injectInjectorOnly (core.js:1767)

Solution

  • Imports should be Inject, and not inject. So, use the following import

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

    And, in the components's constructor

    constructor(public dialogRef: MatDialogRef<TableEditorDialogComponent>,
        @Inject(MAT_DIALOG_DATA) public data: any) { }
    

    Correct Injection of MAT_DIALOG_DATA