我正在开发一个 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>
输出看起来像:
它淡出文本并且下面的衬里发生变化,是否可以将其设为只读?
将 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;
}
您可以将可编辑选择与只读文本框以及它们之间的 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>
您可以用输入框替换 mat-select 表单字段,并将输入框数据与 mat-select 数据绑定。
实际上,您可以使用
panelClass
在只读模式下隐藏选项下拉列表:
.hidden { display: none; }
<mat-select [panelClass]="readonly ? 'hidden' : ''"></mat-select>
今天是2023年11月9日。我正在使用 Angular v16,常规
<select>
。 [attr.readonly]
、 [attr.disabled]
、 [disabled]
都不起作用。
解决方案是
.disabledsel {pointer-events: none;}
[ngClass]="{'disabledsel': condition}"