【问题标题】:How to make select dropdown readonly or disabled conditionally in angular?如何在角度有条件地使选择下拉列表只读或禁用?
【发布时间】:2019-10-01 17:17:15
【问题描述】:

我正在使用 Angular7,我想让选择元素只读或禁用条件。

只读我试过:

  editable: boolean = true;  

还有模板:

 <select  #listOfOptions="ngModel" [(ngModel)]="myList" [readonly]="!editable" class="form-control">
    </select> 

这会导致:

错误:模板解析错误: 无法绑定到“readOnly”,因为它不是“select”的已知属性。

有一个issue关于这个,还没有解决方案!

对于残疾人我试过:

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

无论我如何设置可编辑变量,它总是被禁用。

感谢您的帮助。

【问题讨论】:

    标签: angular typescript angular7


    【解决方案1】:

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

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

    【讨论】:

    • 完美!其他首选选项的任何解决方案 -readonly?
    • 这将无法正常工作,因为它是一个普通的select,因为浏览器会将指令转换为ng-reflect-is-disabled="true"。什么会起作用是@Hien 回答
    【解决方案2】:

    我遇到了与所有者帖子相同的问题。

    我尝试了接受的答案,但它在我这边不起作用。

    我在此链接之后使用[attr.disabled]="!editable ? '' : null" 它有效。

    Angular 4 select disabled is not working

    我为谁担心。

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

    【讨论】:

      【解决方案3】:

      这对您可能并不完全有用,因为我可以看到您正在使用模板驱动表单,但是我建议您将其作为您可能想要研究的替代路线!

      如果您为此切换到使用响应式表单,您可以在初始化表单时设置 disabled 属性。涉及更多的锅炉,我认为这会让一些人脱离反应式表单,但我发现我个人更喜欢他们。

      像这样设置你的 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 }
            ]
          });
        }
      
      }
      

      因此,表单控件现在将“禁用”属性直接绑定到您的局部变量“可编辑”,这应该可以按您的意愿工作。

      【讨论】:

        猜你喜欢
        • 2015-08-17
        • 2023-03-08
        • 1970-01-01
        • 2018-07-16
        • 1970-01-01
        • 2020-05-30
        • 1970-01-01
        • 2019-07-02
        • 1970-01-01
        相关资源
        最近更新 更多