【问题标题】:Sending data using Angular Material Dialog, without closing it, in Angular 9在Angular 9中使用Angular Material Dialog发送数据,而不关闭它
【发布时间】:2020-11-13 07:29:04
【问题描述】:

我使用 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'
    });
}

add-user.component.ts:

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

我该怎么做?

【问题讨论】:

  • 我想到的一件事是使用BehaviorSubject 创建一个服务,您将在父组件中获取数据并在对话框中设置数据
  • 我还没工作,你介绍一个好源码
  • @igor_c 你能想出一个简短的答案,以便问题可以结束,如果它回答了 OP 的问题。

标签: angular typescript angular-material


【解决方案1】:

添加用户组件.ts

public name$ = new Subject<string>();

send () {
  this.name$.next(this.name);
}

还有 app.component.ts

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

  dialogRef.componentInstance.name$
    .pipe(takeUntil(dialogRef.afterClosed()))
    .subscribe((name) => {
      console.log(name);
  });
}

我不确定 takeUntil 在这里是否能正常工作,但你需要在关闭它后以某种方式取消订阅。

【讨论】:

    【解决方案2】:

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

    add-user-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);
    }
    

    add-user.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();
    }
    

    【讨论】:

    • 我明白你的意思,我得到了相对的答复,谢谢
    猜你喜欢
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2018-12-26
    • 2018-09-12
    • 2023-03-29
    相关资源
    最近更新 更多