【问题标题】:Angular 8 - Get data to parent component from popup modal using emiteventAngular 8 - 使用emitevent从弹出模式获取数据到父组件
【发布时间】:2020-11-21 17:09:08
【问题描述】:

我有一个 Angular 8 应用程序,它有一个父组件,在单击按钮时会显示一个弹出模式对话框。当我单击弹出对话框上的保存按钮时,我想将所选对象发送回父组件。

我相信最好的方法是使用 EventEmitter。我在模态对话框中设置了发射器。但是我无法将数据返回给父级。 这就是我所拥有的... 父组件: HTML

 <mat-toolbar color="primary">
    <button
      mat-raised-button
      color="primary"
      id="mat-toolbar__get-rate-button-id"
      [disabled] = !triplegForm.valid
      (click) = "getRates($rateEvent)"
    >
      GET RATE
    </button>
  </mat-toolbar>

TS 代码

 getRates(rateEvent):void{
   let getRateDialog = this.getRateDialog.open(GetRatesComponent, {
      width: '95%',
      height: '80%'
    });

     getRateDialog.afterClosed().subscribe( result => {
       this.selectedRate = result
       console.log("returned from rate dialog: ", this.selectedRate.rateAmount);
     });
  }

弹出模式 HTML

<mat-toolbar>
    <button id="rateModalSave" mat-raised-button color="primary"
            [disabled]="!enableSaveButton()" (click)="saveRate()">SAVE
    </button>
  </mat-toolbar>

TS 代码

export class GetRatesComponent implements OnInit {
  selectedRate: Rate;
  constructor(private  rateService: RateService,
              private dialogRef: MatDialogRef<GetRatesComponent>) {
  }
  ...
 saveRate() {
   console.log("selected rate: ", this.selectedRate);
    this.rateSaved.emit(this.selectedRate);
     this.dialogRef.close();
  }
} 

所以selectedRate 设置在子组件中。 但是父级日志语句中的this.selected.rateAmount 是未定义的。

从孩子发出速率后,我需要关闭弹出窗口。但我没有看到

【问题讨论】:

    标签: angular angular-event-emitter


    【解决方案1】:

    您必须选择:

    1. 使用服务

    2. mat 对话框有这个功能
      在对话 ts

          ...
            saveRate() {
            this.dialogRef.close({value: this.selectedRate});
          }
      

    在父组件中
            ....
            let dialogRef = dialog.open(UserProfileComponent, {
                 height: '400px',
                 width: '600px',
           });
           // here is your value
           dialogRef.afterClosed().subscribe(res => {
            console.log(res.value); // your value!
           });
    

    【讨论】:

    • 那行不通。但我的解决方案是相似的...发布在下面
    【解决方案2】:

    这就是我在上面的答案的帮助下让它工作的方式...... 我将父级中的 getRate 方法更改为: HTML:

     (click) = "getRates()"
    

    TS 代码在父级中是这样的:

     getRates():void{
       let getRateDialog = this.getRateDialog.open(GetRatesComponent, {
          width: '95%',
          height: '80%'
        });
    
       getRateDialog.componentInstance.rateSaved.subscribe((selectedRate) => {
             this.selectedRate = selectedRate;
             console.log("returned from rate dialog: ", this.selectedRate.rateAmount);
        });
      }
    

    模态代码是正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 2018-12-11
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 2016-04-26
      相关资源
      最近更新 更多