如何在Angular2中使用snack-bar(entryComponents)时触发事件

3

我这里有一个方法'confirmSth',动态加载了一个组件'SnackCheckBoxComponent'。

我想知道,在我的OrderDetailComponent中是否可以获取一些信息来区分我从SnackCheckBoxComponent点击的是哪个按钮,以便决定confirmSth返回true还是false。

//...
import { MdSnackBar, MdSnackBarRef } from '@angular/material';

export class OrderDetailComponent {

  constructor(public snackBar: MdSnackBar) {

  confirmSth(): boolean {

    // ...condition
    if (condition) return true

    this.snackBarRef = this.snackBar.openFromComponent(SnackCheckBoxComponent, { duration: 50000 })
    this.snackBarRef.instance.snackBarRefCheckComponent = this.snackBarRef

    // I would like to know If I can get some msg here to distinguish which button i clicked so to decide return true or false.

  }

}

@Component({
  selector: 'snack-check-box',
  templateUrl: './snack-check-box.html',
  styleUrls: ['./snack-check-box.css'],
})
export class SnackCheckBoxComponent {
  public snackBarRefCheckComponent: MdSnackBarRef<SnackCheckBoxComponent>

  private onCancel() {
    alert('clicked option 1');
    this.snackBarRefCheckComponent.dismiss();
  }

  private onSubmit() {
    alert('clicked option 2');
    this.snackBarRefCheckComponent.dismiss();
  }
}

这是我的'./snack-check-box.html'文件。

<span>overloaded, whether to continue xxx</span>

<a (click)="onSubmit()">yes</a>
<a (click)="onCancel()">no</a>
1个回答

3
SnackCheckBoxComponent中创建两个RxJS主题,并使用您绑定的函数调用next值;以下是仅具有提交功能的示例。
export class SnackCheckBoxComponent {
  public submit$ = new Subject<void>()
  public onSubmit() { this.submit$.next(null) }
}

现在从您的 OrderDetailComponent 中,您可以订阅这些事件:
this.snackBarRef.instance.submit$.take(1).subscribe(() => {
  // handle submission here
}

请注意,由于我使用了.take(1),因此您不必手动取消订阅此订阅。该流将在获取一个并且仅有的预期项后结束。或者,您可以在此处使用Observable#toPromise
另外,由于您正在从模板(类外部)访问它们,因此您的onCancelonSubmit必须是public。目前,在JIT模式下,模板未经过类型检查,但您的代码将在AOT中失败,这已成为Angular应用程序的标准。

谢谢你解决我的问题,它起作用了!在你告诉我之前,我不知道主题,哈哈,我要搜索更多关于这个的信息。而且我的函数现在是“公共”的,谢谢! - Gikono

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接