如何向/从ngx-bootstrap模式传递和接收数据?

时间:2018-05-07 04:27:32

标签: angular ngx-bootstrap ngx-bootstrap-modal

可以使用enter image description here将数据传递到模态,但是如何才能接收数据?例如,如果我想创建一个确认对话框?

1 个答案:

答案 0 :(得分:9)

即使目前没有内置方法,也可以通过绑定onHide / onHidden事件来完成。

我们的想法是创建一个Observer,它将订阅onHidden事件并在从它接收数据时触发next()

我正在使用onHidden而不是onHide,因此所有CSS动画都会在返回结果之前完成。

我也在MessageService中实现了它,以便更好地分离代码。

@Injectable()
export class MessageService {
    bsModalRef: BsModalRef;

    constructor(
        private bsModalService: BsModalService,
    ) { }

    confirm(title: string, message: string, options: string[]): Observable<string> {
        const initialState = {
            title: title,
            message: message,
            options: options,
        };
        this.bsModalRef = this.bsModalService.show(ConfirmDialogComponent, { initialState });

        return new Observable<string>(this.getConfirmSubscriber());
    }

    private getConfirmSubscriber() {
        return (observer) => {
            const subscription = this.bsModalService.onHidden.subscribe((reason: string) => {
                observer.next(this.bsModalRef.content.answer);
                observer.complete();
            });

            return {
                unsubscribe() {
                    subscription.unsubscribe();
                }
            };
        }
    }
}

ConfirmDialogComponent如下所示:

export class ConfirmDialogComponent {
    title: string;
    message: string;
    options: string[];
    answer: string = "";

    constructor(
        public bsModalRef: BsModalRef,
    ) { }

    respond(answer: string) {
        this.answer = answer;

        this.bsModalRef.hide();
    }

}

实施后,使用它非常简单:

confirm() {
    this.messageService
        .confirm(
            "Confirmation dialog box",
            "Are you sure you want to proceed?",
            ["Yes", "No"])
        .subscribe((answer) => {
            this.answers.push(answer);
        });
}

您可以在此demo中获取完整代码并查看其运行情况。