Как добавить простое диалоговое окно в мое приложение angular 7? - PullRequest
0 голосов
/ 11 октября 2018

У меня есть приложение в angular 7, где я извлекаю данные из API, загружая данные в таблицу.В конце таблицы есть столбец с кнопкой.Нажатие на эту кнопку вызывает функцию, которая просто записывает данные строки в консоль.Вот мой код для этого:

Мой файл component.ts:

import { HttpClient } from "@angular/common/http";
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { MatTableDataSource } from "@angular/material";
import { Object} from "../object.model";
import {MatDialog, MatDialogRef} from '@angular/material';

@Component({
   styleUrls: ["./styles.scss"],
   templateUrl: "./template.html"
})
export class MyRouteData implements OnInit {
   employeeInfoTable : Object[] = [];
   employeeInfoTableDataSource = new MatTableDataSource(this.employeeInfoTable);
   displayedColumns: string[] = [
     "Name",
     "DateOfBirth",
     "Address",
     "Postcode",
     "Gender",
     "Salary"
     "JobTitle"
     "AdditionalDetails"
  ];

   constructor(private http: HttpClient) {}

   ngOnInit() {
      this.http.get("http://localhost:5000/MyRoute/GetEmployeeInfo")
          .subscribe(response => {
             this.employeeInfoTable = response;
             this.employeeInfoTableDataSource.data = this.employeeInfoTable;
      });
   }

   displayAdditionalDetails(row) {
    console.log("Row sent from link", row);

  }
}

export interface Object{
   id: number;
   Name: string;
   DateOfBirth: Date;
   Address: string;
   Postcode: string;
   Gender: string;
   Salary : number;
   JobTitle : string;
}

Мой файл template.html:

<mat-card style="height: 98%">
  <table mat-table [dataSource]="employeeInfoTableDataSource" class="mat-elevation-z8">
    <ng-container matColumnDef="Name">
        <th mat-header-cell *matHeaderCellDef>Name </th>
        <td mat-cell *matCellDef="let element"> {{element.Name}} </td>
    </ng-container>
    <ng-container matColumnDef="DateOfBirth">
        <th mat-header-cell *matHeaderCellDef> Date Of Birth </th>
        <td mat-cell *matCellDef="let element"> {{element.DateOfBirth}} </td>
    </ng-container>
    <ng-container matColumnDef="Address">
        <th mat-header-cell *matHeaderCellDef> Address </th>
        <td mat-cell *matCellDef="let element"> {{element.Address}} </td>
    </ng-container>
    <ng-container matColumnDef="Postcode">
        <th mat-header-cell *matHeaderCellDef> Postcode </th>
        <td mat-cell *matCellDef="let element"> {{element.Postcode}} </td>

    <ng-container matColumnDef="Gender">
        <th mat-header-cell *matHeaderCellDef> Gender </th>
        <td mat-cell *matCellDef="let element"> {{element.Gender}} </td>
    </ng-container>
    <ng-container matColumnDef="Salary">
        <th mat-header-cell *matHeaderCellDef> Salary </th>
        <td mat-cell *matCellDef="let element"> {{element.Salary}} </td>
    </ng-container>
    <ng-container matColumnDef="JobTitle">
        <th mat-header-cell *matHeaderCellDef> Job Title </th>
        <td mat-cell *matCellDef="let element"> {{element.JobTitle}} </td>
    </ng-container>
    <ng-container matColumnDef="AdditionalDetails">
        <th mat-header-cell *matHeaderCellDef> AdditionalDetails </th>
        <td mat-cell *matCellDef="let element">  <button mat-icon-button color="warn" (click)="displayAdditionalDetails(element)">
          <mat-icon aria-label="Example icon-button with a heart icon">description</mat-icon>
        </button></td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</mat-card>

То, что я хочу сейчас сделать, этопри нажатии кнопки загрузить диалоговое окно.

Я добавил новый HTML-файл под названием dialog-Overview-example-dialog.html, который содержит следующее:

<div mat-dialog-content>
    <p>“I find your lack of faith disturbing.” — Darth Vader</p>

</div>

и IЯ добавил следующее в конец моего файла component.ts, который я получил из какого-то учебника:

@Component({
  selector: "dialog-overview-example-dialog",
  templateUrl: "dialog-overview-example-dialog.html"
})
export class DialogOverviewExampleDialog {
  constructor(public dialogRef: MatDialogRef<DialogOverviewExampleDialog>) {}

  onCloseClick(): void {
    this.dialogRef.close();
  }
}
@Component({
  selector: 'dialog-overview-example',
  templateUrl: 'dialog-overview-example.html',
})

export class DialogOverviewExample {

  constructor(public dialog: MatDialog) {}

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

}

Все, что мне нужно сделать сейчас, это выяснить, как загрузить диалоговое окно из метода displayAdditionalDetails,Со временем я сделаю больше с диалоговым окном, но пока достаточно просто загрузить окно.

Спасибо.

1 Ответ

0 голосов
/ 11 октября 2018

Чтобы открыть диалоговое окно:

  • Убедитесь, что MatDialog введено в ваш класс
  • Используя диалоговое окно, введите dialog.open(component, options)
    • component это то, что вы хотите визуализировать в диалоговом окне
    • options позволяет настраивать поле, а также передавать данные в диалоговое окно

Пример:

@Component({
  styleUrls: ["./styles.scss"],
  templateUrl: "./template.html"
})
export class MyRouteData implements OnInit {

  constructor(private dialog: MatDialog) {}

  displayAdditionalDetails(row) {
    this.dialog.open(DialogOverviewExampleDialog, {
      width: '500px',
      data: row,
    })
  }
}

Это откроет диалоговое окно для вас.Обратите внимание на data: row в опциях.Вот как вы передаете данные в диалоговое окно.

Если вы хотите использовать данные в диалоговом окне, вам необходимо вставить MAT_DIALOG_DATA в ваш диалоговый компонент, например:

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

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

  ngOnInit() {
    console.log(this.data); // this is the "row" passed in
  }

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

}

Если вы используете компиляцию AOT, вам также необходимо добавить все компоненты, отображаемые в виде диалогов, в ваш модуль в entrycomponents:

@NgModule({
  imports: [
    ...
  ],
  declarations: [
    ...
  ],
  entryComponents: [DialogOverviewExampleDialog],
  exports: [
    ...
  ],
})
export class MyModule {
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...