如何将角度组件连接到对话框组件?

时间:2018-08-01 17:25:23

标签: angular angular-material

我正在尝试为删除按钮创建一个确认对话框。我有1个组件用于所有操作,另一个有对话框。我希望当用户单击“删除”按钮时,它将执行在其他组件上实现的方法。这是我的代码。

uploadlist.component.ts

import { Component, OnInit } from '@angular/core';
import { UploadlistService } from '../service/uploadlist.service';
import { CostSpreadsheet } from '../model/costSpreadsheet.model';
import { Http } from '@angular/http';
import { MatDialog, MatDialogConfig, MatDialogRef } from '@angular/material/dialog';

import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { DeleteDialogComponent } from '../shared/delete-dialog/delete-dialog.component';

@Component({
  selector: 'app-uploadlist',
  templateUrl: './uploadlist.component.html',
  styleUrls: ['./uploadlist.component.css']
})
export class UploadlistComponent implements OnInit {

  private costSpreadsheet:CostSpreadsheet [];

  constructor(private _uploadlistService:UploadlistService, public dialog: MatDialog) {   }

  //list files from cost spreadsheet table
  ngOnInit() {
    this._uploadlistService.getFiles().subscribe((costSpreadsheet) => {
      console.log(costSpreadsheet);
      this.costSpreadsheet = costSpreadsheet;
      });
    };

  deleteFile(file: CostSpreadsheet) {
    this._uploadlistService.deleteFile(file).subscribe((data) => {
      this.costSpreadsheet = this.costSpreadsheet.filter(f => f!== file);
    }
  )}; 

 openDialog () {
    const dialogConfig = new MatDialogConfig();
    dialogConfig.disableClose = true;
    this.dialog.open(DeleteDialogComponent, dialogConfig);
  } 
}

uploadlist.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { CostSpreadsheet } from '../model/costSpreadsheet.model';


@Injectable({
  providedIn: 'root'
})
export class UploadlistService {

  private uploadUrl:string = 'http://localhost:8080/bluecost';
  private uploader:string = "X91927";
  private costSpreadsheet = new CostSpreadsheet();

  constructor(private _http:HttpClient) { }

  getFiles(): Observable<CostSpreadsheet[]> {
    return this._http.get<CostSpreadsheet[]>(this.uploadUrl + "/costspreadsheet/" + this.uploader)
    .pipe(catchError(this.handleError('getFiles', [])));
  }

  deleteFile(file: CostSpreadsheet) {
    return this._http.delete(this.uploadUrl + "/spreadsheet/" + file.uploader + "/" + file.fileName, {responseType: 'text'}) 
    .pipe(catchError(this.handleError('deleteFile', [])));
  }

   private handleError<T> (operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {
          console.error(error); // log to console instead
          return of(result as T);
        };
   }    
} 

uploadlist.component.html

<table class="ds-table ds-table-compact order-column stripe cell-border" cellspacing="0">
  <tr>
    <th>File Name</th>
    <th>Number of Records</th>
    <th>Total Amount</th>
    <th></th>
  </tr>
  <tr *ngFor="let f of costSpreadsheet">
    <td>{{ f.fileName }}</td>
    <td>{{ f.noOfRecords }}</td>
    <td>{{ f.totalChargeAmount }}</td>
    <td *ngIf="f.status == 'SUBMITTED'"><button type="submit" class="btn btn-danger" (click)="openDialog(f)">Delete</button></td>
    <td *ngIf="f.status == 'COMPLETED'">SUBMITTED</td>
  </tr>
</table>

delete-dialog.component.ts

import { Component, Output, OnInit, Input, Inject,  EventEmitter, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
import { UploadlistComponent } from '../../uploadlist/uploadlist.component';
import { CostSpreadsheet } from '../../model/costSpreadsheet.model';

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

  private file: CostSpreadsheet;

  constructor(public dialogRef: MatDialogRef<DeleteDialogComponent>) {   }

  ngOnInit() {
    this.dialogRef.updateSize('40%', '40%');
    this.dialogRef.updatePosition({ left: '350px' });     
  }

  delete() {  

  }      

  cancel() {
    this.dialogRef.close();
  }    
}

delete-dialog.component.html

<h2 mat-dialog-title>Delete File</h2>

<mat-dialog-content>
  <h5>Are you sure? This will be permanently deleted.</h5>
</mat-dialog-content>

<mat-dialog-actions>
  <button class="mat-raised-button" (click)="cancel()">Cancel</button>
  <button class="mat-raised-button mat-primary" (click)="delete()">Delete</button>
</mat-dialog-actions>

2 个答案:

答案 0 :(得分:0)

这不是使用对话框的真正方法。通常,确认对话框仅在关闭时返回结果,调用组件将使用该结果执行适当的操作。通常,它是通过close()函数参数或button[matDialogClose]指令,以及通过MatDialogRef.afterClosed()函数来完成的。确认对话框的“结果”通常为是或否-是或否-已确认或取消。因此,一个简单的确认对话框的操作将类似于(部分代码):

<mat-dialog-actions>
  <button class="mat-raised-button" [matDialogClose]="false">Cancel</button>
  <button class="mat-raised-button mat-primary" [matDialogClose]="true">Delete</button>
</mat-dialog-actions>

完全不需要在确认对话框组件中编写任何逻辑-只需发送回用户的操作结果即可。

在您的代码中,由于您已经准备好了很多东西,因此可以使用delete()通过cancel()MatDialogRef.close()函数轻松地返回是/否结果:

delete() {  
  this.dialogRef.close(true);
}      

cancel() {
  this.dialogRef.close(false);
}   

在两种情况下,您都需要在启动对话框的代码中处理确认结果:

this.dialog.open(DeleteDialogComponent).afterClosed().subscribe(result => {
  if (result) {
    // delete
  } else {
    // no action
  }
});

答案 1 :(得分:0)

在这种情况下,EventEmitter或具有BehavioralSubject的共享广播服务可以广播事件似乎很有用。

对于广播服务,请使用RxJs BehaviorSubject发出消息。可以在接收组件中订阅该消息。可以在此link

中看到一个示例