2017-08-12 88 views
0

这里我有一个方法'confirmSth',动态地加载了一个组件'SnackCheckBoxComponent'。如何在angular2中使用快餐栏(entryComponents)时发出事件

我想知道如果我可以在我的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(); 
    } 
} 

这里是SnackCheckBoxComponent在我的 './snack-check-box.html'

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

<a (click)="onSubmit()">yes</a> 
<a (click)="onCancel()">no</a> 

回答

1

创建两个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应用程序的标准。

+0

感谢您解决我的问题,它的工作原理!除非你告诉我,否则我不知道主题,哈哈,我会更多地搜索这个。我的功能现在是'公共',谢谢! – Gikono

相关问题