angular 8 material dialog close button with X top right

烈酒焚心 提交于 2020-08-06 08:11:25

问题


I am trying to get my material dialog to have an X button at the top right, but I am having problems with the positioning.

component.ts

this.d.open(loginComponent, {
  width: '300px',
  height: '',
  panelClass: 'dialogC',
});

component.html

<mat-dialog-content>
    <button mat-button class="close-icon" [mat-dialog-close]="true">
        <mat-icon>close</mat-icon>
    </button>
    <h2 mat-dialog-title>Login</h2>

style.scss

.dialogC {
  position: relative !important;
}

.close-icon {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(50%, -50%);
}

The X is just aligned to the left instead of top right. Suggestions?

Update, this is the problem I get after adding flex:


回答1:


<button class="close" mat-button (click)="onNoClick()">X</button>
<h1 mat-dialog-title>Login</h1>
<div mat-dialog-content>
...
...
</div>

CSS: (Please give it in global (styles.css) or give ViewEncapsulation.NONE or else these styles wont affect.)

.cdk-overlay-pane.my-dialog {
  position: relative!important;
}
.close.mat-button {
  position: absolute;
  top: 0;
  right: 0;
  padding: 5px;
  line-height: 14px;
  min-width: auto;
}

Note that in the CSS We now have a new class out of thin air .my-dialog

So, please mention that as panelClass in dialogRef like below,

this.dialog.open(DialogComponent, {
      width: '250px',
      panelClass: 'my-dialog',
..
..

This yields me the following result,




回答2:


Using mat-icon-button it is necessary to add only the style below to the button.

.close-button{
  float: right;
  top:-24px;
  right:-24px;
}

Functional example:

stackblitz




回答3:


You can have the X at the title and display: flex ? Like this,

<div mat-dialog-title class="flex-container">
  <h1>Login</h1>
   <button mat-button class="close-icon" [mat-dialog-close]="true">
        <mat-icon>close</mat-icon>
    </button>
</div>
<div mat-dialog-content>
...
...
</div>

FlexBox to the rescue,

.flex-container { display: flex;}

SideNote: You can still use fxLayout instead of .flex-container




回答4:


What I prefer is doing something like this -

.html file

<button class="close" mat-button mat-dialog-title (click)="closeDialog()">X</button>

By giving mat-dialog-title to the button I make sure it is in the top layer and then I give custom class to it, something like

.css file

.close.mat-button {
    position: inherit;
    top: 0;
    right: 0;
    padding: 2px;
    line-height: 3px;
    min-width: auto;
  }

The button discussed above and my modal-content is in a parent div, which I display as flex and use as flex-direction: column

.dialog{
    display: flex;
    flex-direction: column;
}

.ts file

  closeDialog() {
    this.dialogRef.close();
  }```


来源:https://stackoverflow.com/questions/58151512/angular-8-material-dialog-close-button-with-x-top-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!