How to make a 'mat-select' readonly?

别说谁变了你拦得住时间么 提交于 2020-12-01 09:16:10

问题


I am working on a angular 5 project. There are many mat-select elements which is supposed to be readonly like text boxes. I found out that there is a disabled feature which is:

  <mat-form-field>
    <mat-select placeholder="Choose an option" [disabled]="disableSelect.value">
      <mat-option value="option1">Option 1</mat-option>
      <mat-option value="option2" disabled>Option 2 (disabled)</mat-option>
      <mat-option value="option3">Option 3</mat-option>
    </mat-select>
  </mat-form-field>

which out put looks like:

It fades out the text and the lining below get changes, is it possible to make it readonly?


回答1:


Add CSS to both select block and mat-form-field block, these can be applied automatically to all the select elements:

<mat-form-field class="readonly-wrapper">
  <mat-select class="readonly-block" placeholder="Choose an option" [disabled]="disableSelect.value">
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2" disabled>Option 2 (disabled)</mat-option>
    <mat-option value="option3">Option 3</mat-option>
  </mat-select>
</mat-form-field>  

CSS code:

.readonly-wrapper {
    cursor: not-allowed;
}

.readonly-wrapper .readonly-block {
    pointer-events: none;
}



回答2:


You can combine an editable select with a readonly textbox and ngIf between them:

  <mat-form-field>
    <mat-label>Choose an option</mat-label>
    <input *ngIf="!editing" mat-input formControlName="mySelect" [readonly]="true">
    <mat-select *ngIf="editing" formControlName="mySelect">
      <mat-option value="option1">Option 1</mat-option>
      <mat-option value="option2" disabled>Option 2 (disabled)</mat-option>
      <mat-option value="option3">Option 3</mat-option>
    </mat-select>
  </mat-form-field>


来源:https://stackoverflow.com/questions/51035871/how-to-make-a-mat-select-readonly

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