首页 文章

在角度材质中调用Dialog组件内的组件

提问于
浏览
1

我有2个组件叫
1) demo
2) add-customer

demo 组件中,我有一个名为add的 button . 单击该按钮时,将调用一个函数(例如 openDialog() )来打开一个 dialog 窗口(i,e op-up窗口) . 现在我想在 dialog 窗口中调用 add-customer 组件 .
我怎样才能做到这一点 . 这是stackblitz链接 .

2 回答

  • 2

    Demo.component.ts您需要将组件“插入”到对话框中 .

    import {AddCustomerComponent} from '../add-customer/add-customer.component'
    
     openDialog(): void {
        const dialogRef = this.dialog.open(AddCustomerComponent, {
          width: '450px',
        });
    

    app.module.ts,将对话框中加载的组件添加到entryComponents中

    declarations: [
        AppComponent,
        DemoComponent,
        AddCustomerComponent,
        ],
    entryComponents: [
        AddCustomerComponent
    ],
    

    编辑:要取消关闭,您必须在add-customer.component.html上的取消按钮上添加一个单击功能

    <button mat-raised-button type="button" class="Discard-btn" (click)="cancel()">Cancel</button>
    

    然后在.ts文件中添加该函数,并在构造函数上注入dialogRef

    import {MatDialogRef} from '@angular/material';
    
    constructor(private fb: FormBuilder,
                  private dialogRef: MatDialogRef<AddCustomerComponent>) {}
    
        public cancel() {
           this.dialogRef.close();
        }
    
  • 3

    您必须首先将要创建的组件动态添加为模块的入口组件 .

    @NgModule({
      imports: [
      ],
      declarations: [
        AppComponent,
        DemoComponent,
        AddCustomerComponent,
        ],
      bootstrap: [AppComponent],
      providers: [],
      entryComponents: [AddCustomerComponent] // This line
    })
    

    然后,您必须使用由角度材质公开的方法来添加创建所需的组件

    let dialogRef = dialog.open(AddCustomerComponent, {
      height: '400px',
      width: '600px',
    });
    

    这应该按预期工作 .

    你可以看到它工作Here

相关问题