在对话框中实现组件的关闭按钮

问题描述 投票:0回答:1

我有一个组件 A,通常应该在没有关闭按钮的情况下显示。但是,当我在对话框中打开组件 A 时,我想添加一个关闭按钮来关闭对话框。

如何在 Angular 中实现此行为?有没有一种优雅的方法来确定组件是否在对话框中打开,以便我可以相应地添加关闭按钮?

预先感谢您的协助!

这是我的代码: https://stackblitz.com/edit/stackblitz-starters-p4pfnr?file=src%2Fapp%2Fb%2Fb.component.ts

angular angular-material
1个回答
0
投票

是的,我们可以使用

data
方法第二个参数的
open
属性。我们将属性
fromPopup
设置为 true,然后在我们的组件上读取它!

b ts

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

@Component({
  selector: 'app-b',
  standalone: true,
  imports: [AComponent],
  templateUrl: './b.component.html',
  styleUrl: './b.component.css',
})
export class BComponent {
  constructor(public dialog: MatDialog) {}

  public openDialog() {
    this.dialog
      .open(AComponent, {
        data: { fromPopup: true },
      })
      .afterClosed()
      .subscribe((res) => {
        console.log(res);
      });
  }
}

b html

<button (click)="openDialog()" mat-raised-button color="primary" type="button">
  Open Dialog
</button>

<app-a />

一个ts

import { Component, Inject, Optional } from '@angular/core';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { FormControl, FormGroup } from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-a',
  standalone: true,
  imports: [
    FormsModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    CommonModule,
    MatDialogModule,
  ],
  templateUrl: './a.component.html',
  styleUrl: './a.component.css',
})
export class AComponent {
  form!: FormGroup;
  fromPopup = false;

  constructor(
    @Optional() @Inject(MAT_DIALOG_DATA) public data: { fromPopup: boolean }
  ) {
    this.fromPopup = !!data?.fromPopup;
    this.form = new FormGroup({
      email: new FormControl(''),
    });
  }
}

一个html

<form [formGroup]="form" class="">
  <h1>App A</h1>

  <mat-form-field>
    <mat-label>Email</mat-label>
    <input
      matInput
      type="email"
      formControlName="email"
      placeholder="Ex. [email protected] "
    />
  </mat-form-field>

  <button mat-button type="button" color="primary">Save</button>
</form>
<button *ngIf="fromPopup" mat-button [mat-dialog-close]="true">
  shows only for popup!
</button>

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.