Stackblitz 简单的 MatDialog 示例无法找到 ComponentFactory

Stackblitz simple MatDialog example unable to find ComponentFactory

我正在尝试设置 stackblitz example 以针对我在测试中遇到的问题提出更复杂的问题。

但是,在设置基本示例时,当我的基本测试通过时,单击按钮让 MatDialog 显示时会抛出找不到 ComponentFactory 的错误。但是我已经将它添加到 app.module.ts 中的 declarations 和 entryComponent 中。我错过了什么?

p.s。代码本身适用于我的大型项目,这似乎与我在 Stackblitz 中设置它的方式有关,这似乎是问题所在。

p.p.s 根据 Maihan 在下面的回答,它让我开始思考这个想法本身。即使它构建并且 运行,这个想法也会抱怨无法找到 AddUserDialog 组件。但不知道为什么。

app.component.ts

import { Component } from '@angular/core';
import { MatDialog, MatDialogConfig } from '@angular/material';
import { AddUserDialogComponent } from './AddUserDialogComponent';

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

constructor(public dialog: MatDialog){
};

openAddUserDialog(): void{
   const dialogConfig = new MatDialogConfig();

   dialogConfig.data = {
        employeeList:['foo', 'bar'],
        roles: ['fiz', 'faz']
    };

   const dialogRef = this.dialog.open(AddUserDialogComponent, dialogConfig);

   dialogRef.afterClosed().subscribe((data) => {
   console.log('hello');
   });
 }
}

app.module.ts

import { NgModule } from '@angular/core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { MatDialogModule, MatDialogRef, MatDialog } from '@angular/material/dialog';
import { AddUserDialogComponent } from './AddUserDialogComponent';

import { AppComponent } from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, MatDialogModule, NoopAnimationsModule ],
  declarations: [ AppComponent, AddUserDialogComponent ],
  exports: [AppComponent, AddUserDialogComponent],
  entryComponents: [ AddUserDialogComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts@angular/material/dialog 导入:

import { MatDialog, MatDialogConfig } from '@angular/material/dialog';

而不是:

import { MatDialog, MatDialogConfig } from '@angular/material';

并为 root 注入它。如果您在服务中或延迟加载模块中使用它,通常会发生这种情况。

@Injectable({ providedIn: 'root' })
export class AddUserDialogComponent implements OnInit {}

您正在动态加载 AddUserDialogComponent,因此,您添加了 app.module.ts > entryComponents。您需要在测试单元中执行相同的操作:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [RouterTestingModule, MatDialogModule, NoopAnimationsModule],
    providers: [AddUserDialogComponent],
    declarations: [AppComponent, AddUserDialogComponent]
  })
    .overrideModule(BrowserDynamicTestingModule, {
      set: { entryComponents: [AddUserDialogComponent] }
    })
    .compileComponents();
}));

此外,将 <my-app></my-app> 添加到您的 index.html 以消除控制台中的以下错误:

The selector "my-app" did not match any elements