可以使用MatDialogRef的injector来将数据注入到dialog中,然后在模板中使用它们。这样可以使模板中的数据属性更直接、更简洁。
以下是可以将数据注入到dialog中并在模板中引用它们的示例代码:
// Component that opens dialog import { Component } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { DialogComponent } from './dialog/dialog.component';
@Component({
selector: 'app-root',
template:
,
})
export class AppComponent {
constructor(private dialog: MatDialog) {}
openDialog(): void { const dialogRef = this.dialog.open(DialogComponent, { data: { name: 'John', age: 30 }, }); } }
// DialogComponent import { Component, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
@Component({
selector: 'app-dialog',
template: You are {{ age }} years old.
,
})
export class DialogComponent {
constructor(
public dialogRef: MatDialogRefWelcome {{ name }}
get name(): string { return this.data.name; }
get age(): number { return this.data.age; } }
在DialogComponent中,使用MAT_DIALOG_DATA注入数据。然后,我们可以获取它们并将它们绑定到模板中的属性。
这样做可以使模板更简洁,更容易理解。