【问题标题】:Angular 10 / How to share 1 variable between 1 file with 2 classes / Angular Material Dialog componentAngular 10 / 如何在 1 个文件和 2 个类之间共享 1 个变量 / Angular Material Dialog 组件
【发布时间】:2021-02-08 16:18:14
【问题描述】:

我正在使用具有以下结构的 Angular Material Dialog 组件:

import {Component, Inject} from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';

export interface DialogData {
  animal: string;
  name: string;
}

/**
* @title Dialog Overview
*/
@Component({
  selector: 'dialog-overview-example',
  templateUrl: 'dialog-overview-example.html',
})
export class DialogOverviewExample {

 animal: string;
 name: string;

constructor(public dialog: MatDialog) {}

openDialog(): void {
 const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
   width: '250px',
   data: {name: this.name, animal: this.animal}
});

 dialogRef.afterClosed().subscribe(result => {
   console.log('The dialog was closed');
   this.animal = result;
   });
 }
}

 @Component({
     selector: 'dialog-overview-example-dialog',
     templateUrl: 'dialog-overview-example-dialog.html',
   })
   export class DialogOverviewExampleDialog {

   constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) {}

    onNoClick(): void {
      this.dialogRef.close();
    }

 }

    

如您所见,它有 2 个类,但只有 1º 类包含在父组件 .html 中

 <app-filter-modal [requestForm]="requestForm" [name]="name" 
 [animal]="animal"></app-filter-modal>

我需要链接出一个@Input,这是一个父组件变量与 2º 类(创建模态窗口本身的类)具有相同名称的变量:

[requestForm]="requestForm"

但是我遇到了一个错误,因为我不能在 2º 类选择器中包含上面的行,因为 Angular Material Dialog 不能这样工作。

如何将父组件变量requestForm与同名的2º类Angular Material Dialog变量(requestForm)联系起来。我的第一个想法是在包含两者的文件中的两个类之间共享变量。

【问题讨论】:

  • 您可以通过 Input 装饰器将数据传递到“DialogOverviewExample”组件中,然后从那里将数据数据传递到 mat 对话框组件中。

标签: angular angular-material


【解决方案1】:

就像你对“名字”和“动物”所做的那样。 (尽管缺少 @Input 装饰器)

将 requestForm 添加到 DialogData 中

export interface DialogData {
  animal: string;
  name: string;
  requestForm: any;
}

在对话框打开器组件中创建输入。

@Component({
  selector: 'dialog-overview-example',
  templateUrl: 'dialog-overview-example.html',
})
export class DialogOverviewExample {
 @Input() requestForm: string;

打开时发送到对话框

openDialog(): void {
 const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
   width: '250px',
   data: {
     name: this.name, 
     animal: this.animal,
     requestForm: this.requestForm
   }
});

【讨论】:

  • 谢谢,你的想法行得通,但是在对话框类的构造函数中注入数据对象也是必要的:export class YourDialog { constructor(@Inject(MAT_DIALOG_DATA) public data: {name: string}) { } }
猜你喜欢
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多