【问题标题】:How to emit event when using snack-bar (entryComponents) in angular2在angular2中使用小吃吧(entryComponents)时如何发出事件
【发布时间】:2017-08-12 08:04:26
【问题描述】:

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

我想知道我是否可以在我的 OrderDetailComponent 中获取一些消息,以区分我单击了 SnackCheckBoxComponent 中的哪个按钮,以便决定 confirmSth 返回真或假。

//...
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>

【问题讨论】:

    标签: angular angular-material2


    【解决方案1】:

    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 中会失败,而 AOT 正在成为 Angular 应用程序的标准。

    【讨论】:

    • 感谢您解决了我的问题,它有效!直到你告诉我,我才知道主题,哈哈,我要去搜索更多关于这个的内容。我现在的功能是public,谢谢!
    猜你喜欢
    • 2020-02-20
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多