angular - 如何将数据从 Angular Material 对话框传递到父组件?

标签 angular typescript angular-material angular6

我使用的是 angular 6,我有一个可以打开对话框的按钮。在我的对话框中,我有一个获取用户数据的表单,然后我有两个按钮可以提交和取消。我试图在控制台中显示我的表单数据,但它返回未定义!有什么问题?这是部分代码:

ma​​in.component.ts:

import { Work } from '../../../../classes/work_shift';
import { DialogContentComponent} from './dialog-content/dialog-content.component';
export class WorkShiftsComponent implements OnInit {
 shifts: Work[];
  name: string;
  start: string;
  end: string;
  constructor(public dialog: MatDialog, private shiftService: WorkShiftsService) { }

  ngOnInit() {
  }

  openDialog() {
    const dialogRef = this.dialog.open(DialogContentComponent, {
      width: '640px',
      disableClose: true,
      data: {name: this.name, start: this.start, end: this.end}
    });
    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      console.log(result);//returns undefined
    });
  }
}

dialogContent.component.html:

    <mat-dialog-content>
  <form class="example-form">
    <div fxLayout="column" fxLayoutAlign="space-around" class="form">
      <div class="input">
        <mat-form-field class="input4">
          <input matInput placeholder="Shift name">
        </mat-form-field>
      </div>
      <div>
        <mat-form-field class="input input2">
          <input matInput placeholder="Start" atp-time-picker>
        </mat-form-field>
        <mat-form-field class="input input2">
          <input matInput placeholder="End" atp-time-picker >
        </mat-form-field>
      </div>
      <br/>
    </div>
  </form>
</mat-dialog-content>
<mat-dialog-actions>
  <button class="mat-button" mat-button (click)="onClose()">Cancel</button>
  <button class="mat-button" mat-button [mat-dialog-close]="data" cdkFocusInitial color="primary">Create</button>
</mat-dialog-actions>

最佳答案

查看完整教程 Link

只需在close() 方法中将数据从Dialog 组件传回给父组件

enter image description here

//dialog-box.component.ts
import { Component, Inject, Optional } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

export interface UsersData {
  name: string;
  id: number;
}


@Component({
  selector: 'app-dialog-box',
  templateUrl: './dialog-box.component.html',
  styleUrls: ['./dialog-box.component.css']
})
export class DialogBoxComponent {

  action:string;
  local_data:any;

  constructor(
    public dialogRef: MatDialogRef<DialogBoxComponent>,
    //@Optional() is used to prevent error if no data is passed
    @Optional() @Inject(MAT_DIALOG_DATA) public data: UsersData) {
    console.log(data);
    this.local_data = {...data};
    this.action = this.local_data.action;
  }

  doAction(){
    this.dialogRef.close({event:this.action,data:this.local_data});
  }

  closeDialog(){
    this.dialogRef.close({event:'Cancel'});
  }

}

然后返回父组件中的事件和数据对象/值

//app.component.ts
import { Component, ViewChild } from '@angular/core';

import { MatDialog, MatTable } from '@angular/material';
import { DialogBoxComponent } from './dialog-box/dialog-box.component';

export interface UsersData {
  name: string;
  id: number;
}

const ELEMENT_DATA: UsersData[] = [
  {id: 1560608769632, name: 'Artificial Intelligence'},
  {id: 1560608796014, name: 'Machine Learning'},
  {id: 1560608787815, name: 'Robotic Process Automation'},
  {id: 1560608805101, name: 'Blockchain'}
];
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  displayedColumns: string[] = ['id', 'name', 'action'];
  dataSource = ELEMENT_DATA;

  @ViewChild(MatTable,{static:true}) table: MatTable<any>;

  constructor(public dialog: MatDialog) {}

  openDialog(action,obj) {
    obj.action = action;
    const dialogRef = this.dialog.open(DialogBoxComponent, {
      width: '250px',
      data:obj
    });

    dialogRef.afterClosed().subscribe(result => {
      if(result.event == 'Add'){
        this.addRowData(result.data);
      }else if(result.event == 'Update'){
        this.updateRowData(result.data);
      }else if(result.event == 'Delete'){
        this.deleteRowData(result.data);
      }
    });
  }

  addRowData(row_obj){
    var d = new Date();
    this.dataSource.push({
      id:d.getTime(),
      name:row_obj.name
    });
    this.table.renderRows();

  }
  updateRowData(row_obj){
    this.dataSource = this.dataSource.filter((value,key)=>{
      if(value.id == row_obj.id){
        value.name = row_obj.name;
      }
      return true;
    });
  }
  deleteRowData(row_obj){
    this.dataSource = this.dataSource.filter((value,key)=>{
      return value.id != row_obj.id;
    });
  }


}

关于angular - 如何将数据从 Angular Material 对话框传递到父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51815455/

相关文章:

angular - 如何为垫卡添加垫分页器?

java - 如何使用 Angular 4 在 Spring Boot 中显示存储的图像?

php - DarkaOnline Swagger-php 生成错误的界面

angular - 使用纯 CSS 更改 Material 2 中的单选按钮颜色

typescript 找不到模块

javascript - RxJS:forkJoin 似乎不起作用

angular - 我应该在 Angular 2 中使用什么 UI 前端框架

javascript - 使用 *ngFor 并从 ion-label 中检索 html 文本

node.js - 错误 : EACCES: permission denied, mkdir '/usr/local/lib/node_modules/node-sass/build'

angular - 类型 'zip' 上不存在属性 'typeof Observable'。 Angular 6