如何使“垫选择”只读?

问题描述 投票:0回答:5

我正在开发一个 Angular 5 项目。有许多

mat-select
元素应该像文本框一样是只读的。我发现有一个
disabled
的功能,那就是:

  <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>

输出看起来像:

它淡出文本并且下面的衬里发生变化,是否可以将其设为只读?

angular angular-material angular5
5个回答
22
投票

将 CSS 添加到选择块和 mat-form-field 块,这些可以自动应用于所有选择元素:

<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代码

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

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

19
投票

您可以将可编辑选择与只读文本框以及它们之间的 ngIf 组合起来:

  <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>

2
投票

您可以用输入框替换 mat-select 表单字段,并将输入框数据与 mat-select 数据绑定。


1
投票

实际上,您可以使用

panelClass
在只读模式下隐藏选项下拉列表:

.hidden { display: none; }
<mat-select [panelClass]="readonly ? 'hidden' : ''"></mat-select>

0
投票

今天是2023年11月9日。我正在使用 Angular v16,常规

<select>
 [attr.readonly]
 [attr.disabled]
 [disabled]
都不起作用。

解决方案是

  • .css
    .disabledsel {pointer-events: none;}
  • html
    [ngClass]="{'disabledsel': condition}"
© www.soinside.com 2019 - 2024. All rights reserved.