首页 > 解决方案 > 如何获取位于其他组件中的数组?(模板,*ngComponentOutlet 和 AngularMaterialDialog)

问题描述

角度 7,角度材料 7

GalleryComponent,其中列出了图像,用户可以选择其中一些:

@Component({
  selector: 'app-gallery',
  template: `

    <mat-card *ngFor="let file of files" (click)="toggleSelect(file)">
      <img mat-card-image [src]="file.url">
    </mat-card>

  `
})
export class GalleryComponent {
  selected: Array<FileDetails> = [];
  files: Array<FileDetails> = [{url: 'someurl1'}, {url: 'someurl2'}];

  toggleSelect(file: FileDetails): void {
    const indexInArray = this.selected.findIndex(f => f === file);
    indexInArray !== -1 ? this.selected.splice(indexInArray, 1) : this.selected.push(file);
  }
}

在另一个组件(PartnersEditTableComponent)中,我想在模板中重用 Gallery 组件,在模态/对话框(Angular Material Dialog)中打开。

@Component({
  selector: 'app-partners-edit-table',
  template: `

    <button mat-icon-button (click)="openGallery()">
      <mat-icon>collections</mat-icon>
    </button>

    <ng-template #galleryModal>
      <h2 mat-dialog-title>Gallery</h2>
      <mat-dialog-content>
        <ng-container *ngComponentOutlet="GalleryComponent"></ng-container>
      </mat-dialog-content>
      <mat-dialog-actions align="end">
        <button mat-raised-button [mat-dialog-close]="false">Close</button>
        <button mat-raised-button color="primary" [mat-dialog-close]="GalleryComponent.selected">Select</button>
      </mat-dialog-actions>
    </ng-template>

  `
})
export class PartnersEditTableComponent {
  @ViewChild('galleryModal') private readonly galleryModal;
  GalleryComponent = GalleryComponent;

  constructor(private matDialog: MatDialog) {
  }

  openGallery(): void {
    this.matDialog.open(this.galleryModal).afterClosed().subscribe((selectedItems) => {
      if (selectedItems) {
        // do something with selectedItems array
      }
    });
  }
}

如果用户单击对话框上的“选择”按钮,我想获得“选定”数组,如:

[mat-dialog-close]="GalleryComponent.selected"

->

this.matDialog.open(this.galleryModal).afterClosed().subscribe((selectedItems) => {
  if (selectedItems) {
    // do something with selectedItems array
  }
});

这有可能以某种方式做到这一点吗?

标签: angularangular-material

解决方案


您可以从对话框 ref 传递数据

this.dialogRef.close("YOUR_DATA");

或在 HTML 中使用

  <button mat-button [mat-dialog-close]="'YOUR_DATA'">Ok</button>

然而,这意味着您的 GalleryComponent 需要知道它是一个MatDialog.

你可以通过注入它来做到这一点

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

现在对您来说有一个棘手的部分,因为通常您不会在模式内部和外部使用组件。但是,您可以通过将字段标记为可选并在使用前检查它们是否为空来实现这一点

  constructor(
    @Optional() public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Optional() @Inject(MAT_DIALOG_DATA) public data: DialogData | any) {
  }

  onNoClick(): void {
    if (this.dialogRef)
      this.dialogRef.close("Stefan");
  }

您可以在这里找到一个工作示例:https ://stackblitz.com/edit/angular-uy8uwe


推荐阅读