如何在Angular中有条件地使选择下拉框只读或禁用?

10

我正在使用 Angular7,我想让

4个回答

13

你应该使用 disabled 而不是 attr.disabled

<select [disabled]="!editable">
...
</select>

完美!有没有其他首选项-只读的解决方案? - TiyebM
2
这不会正常工作,因为它是一个普通的 select,因为浏览器将指令转换为 ng-reflect-is-disabled="true"。有效的方法是使用 @Hien 的答案。 - Mazen Ak
@TiyebM 你可以使用 [readOnly]="!editable"。 - Shridhar Sharma

13

我也遇到了所有者发布帖子的同样问题。

我尝试了接受的答案,但在我的情况下它没有起作用。

我使用了[attr.disabled] = "!editable ? '' : null",按照这个链接它起作用了。

Angular 4 select disabled is not working

我分享给关心此问题的人。

<select [attr.disabled]="!editable ? '' : null">
  <option></option>
</select>

5

我知道你正在使用模板驱动表单,所以这可能对你没有很大的用处,但是我会建议你尝试一下另外一种替代方案!

如果你改用响应式表单,就可以在初始化表单时设置禁用属性。需要更多样板代码,这也是一些人不喜欢使用响应式表单的原因之一,但我个人却比较喜欢它们。

请按如下方式设置HTML:

<form [formGroup]="selectForm">
  <select formControlName="mySelect">
    <!-- Put your options in here with an *ngFor over an array in your component -->
  </select>
</form>

然后按照以下方式设置您的组件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
// Note: You will need to import the ReactiveFormsModule in your nearest local ngModule

@Component({...})
export class MyComponent implements OnInit {

  public selectForm: FormGroup;
  public editable: boolean;
  public options: any[];

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.selectForm = this.formBuilder.group({
      mySelect: [
        { value: '', disabled: !editable }
      ]
    });
  }

}

所以表单控件现在将直接绑定到您的本地变量“editable”的“disabled”属性,这应该可以按照您的要求工作。

0
在任何不起作用的情况下,这是我所做的。我将mat-form-field封装在一个div中,将指针事件设置为none,并将不透明度更改为.5,以模拟只读或禁用状态。
<div
  [style.pointer-events] = "DisableDocumentType(documentIndex) ? 'none' : 'auto'"
  [style.opacity] = "DisableDocumentType(documentIndex) ? .5 : 1"
>
  <mat-form-field appearance="outline" style="width:10vw; align-content: end;">
    <mat-label> {{'app.documentType' | translate}}*</mat-label>
    <mat-select
      formControlName="documentType"
      (selectionChange)="changeDocumentType($event.value, documentIndex)"
    >
      <mat-option [value]="documentType.code" *ngFor="let documentType of documentTypes">{{documentType.name | translate}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接