首页 > 解决方案 > 在Angular 9中使用Angular Material Dialog发送数据,而不关闭它

问题描述

我使用 Angular 9,我正在使用 Angular Material 中的对话框功能,您可以看到其中的示例。我想在某个时候向主要组件发送信息,而不关闭对话框。 https://material.angular.io/components/dialog/examples

我可以在不关闭对话框的情况下发送数据,而不是使用以下代码

this.dialogRof.colse(data);

例子:

app.component.html:

<button (click)="addUser()">

app.component.ts:

addUser(){
    const dialogRef = this.dialog.open(AddUser, {
      width: '350px'
    });
}

添加用户.component.ts:

name="Aliakbar";
send(){
  // Send name to app-component without closing add-user-component
}

我怎样才能做到这一点?

标签: angulartypescriptangular-material

解决方案


我的想法是创建一个简单的服务,该服务将保存对话框中的数据,并且可以从父组件中获取这些数据。

添加用户-dialog.service.ts

private name = new BehaviorSubject<string>(undefined);

constructor(
  ...
  private addUserDialogService: AddUserDialogService,
  ...
) {}

getName() {
  return this.name.asObservable();
}

setName(name: string) {
  this.name.next(name);
}

添加用户.component.ts

name = 'Aliakbar';

constructor(
  private addUserDialogService: AddUserDialogService,
) { }

send() {
  this.addUserDialogService.setName(this.name);
}

app.component.ts

addUserDataSubscription: Subscription;

constructor(
  ...
  private addUserDialogService: AddUserDialogService,
  ...
) {}

ngOnInit() {
  this.addUserDataSubscription = this.addUserDialogService.getName().subscribe(name => {
    // do what you need with the dialog data
  }
}

ngOnDestroy() {
  this.addUserDataSubscription.unsubscribe();
}

推荐阅读