【发布时间】:2017-12-28 15:19:23
【问题描述】:
我有一个组件,它打开一个模式对话框,让用户输入两个日期。然后,我想将这两个日期保存到组件后面的 db 模型中,但我无法确定何时何地获得这些结果。
需要明确的是:我目前可以在我的主组件模板中将对话框结果视为两个日期,但我想知道,在...某些方法...在我的主组件中,当对话框关闭并且日期不再是空值——所以我可以将它们保存到数据库中。
我的主组件模板有一个带有 onClick 事件的按钮:
<a class="btn btn-sm role="button"><mat-icon title="Get Dates" (click)="onClickGetDates(appt)">flag</mat-icon></a> Result from dialog: {{ dateRangeArray }}
主组件实现onClick事件:
onClickGetDates(appt) {
this.dialogService
.confirmDateRange('Get Dates', 'Enter two dates:',
appt.beginDate, appt.endDate)
.subscribe(res => this.dateRange = res);
.
.
// I would like to now save the dateRange result to my database, but at this point, result is [null,null], so the code below does nothing (except null out the dates):
appt.beginDate = dateRange[0];
appt.endDate = dateRange[1];
this.apptdata.updateAppt(appt);
}
这里是confirmDateRange,定义在一个Dialog Service中,它实际上显示了对话框:
public confirmDateRange(title: string, message: string, begin: Date, end: Date): Observable<boolean> {
let dialogRef: MatDialogRef<ConfirmDialogComponent>;
dialogRef = this.dialog.open(ConfirmDialogComponent);
dialogRef.componentInstance.title = title;
dialogRef.componentInstance.message = message;
dialogRef.componentInstance.beginDate = begin;
dialogRef.componentInstance.endDate = end;
return dialogRef.afterClosed();
}
还有对话框组件:
export class ConfirmDialogComponent implements OnInit {
public title: string;
public message: string;
public beginDate: Date;
public endDate: Date;
constructor(public dialogRef: MatDialogRef<ConfirmDialogComponent>) { }
ngOnInit() {
}
还有对话框的模板:
<h2>{{ title }}</h2>
<hr>
<p>{{ message }}</p>
<!--Date Picker Begin-->
<mat-form-field>
<input matInput [matDatepicker]="beginDatePicker" placeholder="Beginning" [(ngModel)]="beginDate">
<mat-datepicker-toggle matSuffix [for]="beginDatePicker"></mat-datepicker-toggle>
<mat-datepicker #beginDatePicker></mat-datepicker>
</mat-form-field>
<!--Date Picker End-->
<mat-form-field>
<input matInput [matDatepicker]="endDatePicker" placeholder="Ending" [(ngModel)]="endDate">
<mat-datepicker-toggle matSuffix [for]="endDatePicker"></mat-datepicker-toggle>
<mat-datepicker #endDatePicker></mat-datepicker>
</mat-form-field>
<!--OK-->
<button type="button" mat-raised-button
(click)="dialogRef.close([beginDate, endDate])">OK</button>
<!--Cancel-->
<button type="button" mat-button
(click)="dialogRef.close()">Cancel</button>
在对话框中单击“确定”后,我可以在主组件的模板中看到带有两个日期的结果数组,如下所示:Result from dialog: {{ dateRangeArray }}。尝试在 onClickGetDates 中访问相同的结果“为时过早”,结果是一个空数组......那么,在哪里/何时是在我的主要组件中查看该结果的合适位置?
我觉得我误用了对话框的 AfterClose() 事件,并且我应该能够在该事件触发后立即检索结果,但我仍然对 Angular 太陌生,无法意识到我在做什么做错了。
【问题讨论】:
-
首先,我强烈建议您不要将 Bootstrap 与 Angular Material 混合使用,因为样式可能会相互冲突。其次,
MatDialogRef#afterClosed返回一个 observable,其结果是通过组件模板中的matDialogClose属性或MatDialogRef#close指定的值,这允许指定可选的结果参数。
标签: angular angular-material modal-dialog