Σάββατο 13 Ιουνίου 2020

Open a Material DialogRef with CSS positioning, injection of MAT_DIALOG_DATA, and pass dialog data in caller








Angular Material Dialog 


 Button to open dialog:

Dialog data from parent / edit city:

Change visible in parent component:










1. Parent Component - HTML



<div style="height: 800px">
    <div style="height: 200px" fxLayout="row" fxLayoutAlign="center center">
        <div fxLayout="column" fxLayoutAlign="center center">
            <p>User Name: {{userName}}</p>
            <p>User City: {{userCity}}</p>
            <button (click)="openMatDialog()" mat-button color="primary">Update User's town</button>
        </div>
    </div>
</div>



2. Parent Component TS


import {Component, OnInit} from '@angular/core';
import {MatDialog} from '@angular/material/dialog';
import {TestDialogCompComponent} from 'app/home/test-dialog-comp/test-dialog-comp.component';
@Component({
  selector: 'jhi-test-comp',
  templateUrl: './test-comp.component.html',
  styleUrls: ['./test-comp.component.scss']
})
export class TestCompComponent implements OnInit {
  userName = 'Peter';
  userCity = 'Athens';
  constructor(public dialog: MatDialog) { }
  ngOnInit() {}
  openMatDialog(): void {
    const dialogRef = this.dialog.open(TestDialogCompComponent, {
      position: {bottom: '100px'},
      data: { userName: this.userName, userCity: this.userCity }
    });
    dialogRef.afterClosed().subscribe(result => {
      this.userCity = result;
    });
  }
}




3. Dialog Component - HTML


<h2 mat-dialog-title>Dialog</h2>
<mat-dialog-content class="text">
    <table>
        <tr>Name : {{data.userName}}</tr>
    </table>
    City:
    <mat-form-field>
        <input matInput [(ngModel)]="data.userCity">
    </mat-form-field>
</mat-dialog-content>
<mat-dialog-actions style="text-align: center">
    <button mat-raised-button [mat-dialog-close]="data.userCity" color="primary">Save</button>
</mat-dialog-actions>





4. Dialog Component - TS


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

@Component({
  selector: 'jhi-test-dialog-comp',
  templateUrl: './test-dialog-comp.component.html',
  styleUrls: ['./test-dialog-comp.component.scss']
})
export class TestDialogCompComponent implements OnInit {

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

  ngOnInit() {}

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

}





5. Dialog Component - CSS



.mat-dialog-content {
  height: 70%;
  width: 100%;
}



6. App.module.ts


Add parent and dialog component to @NgModule entryComponents

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

What may be missing, or could get better?