【问题标题】:To enable or disable the input field based on the value of select component in angular根据角度中选择组件的值启用或禁用输入字段
【发布时间】:2018-10-03 04:43:34
【问题描述】:

我有 2 个组件 selectinput 组件。如下图所示。

场景:默认情况下,我将 input 字段设置为 disabled。如果我从 select 中选择某个选项> 组件然后该字段变为活动状态。此方案工作正常。

预期结果: 我应该在 select 组件(即下拉菜单)中有另一个选项来再次禁用输入字段(如果用户不想从选择组件中选择任何内容)。

这是stackblitz 链接。

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    您必须进行一些编辑。在您的 Html 文件中

    <mat-form-field class="id-name">
            <mat-select placeholder="ID Card" formControlName="IDproof" (ngModelChange)="onChange($event)">
                <mat-option *ngFor="let IDproof of  IDproofs" [value]="IDproof.value">
                    {{IDproof.viewValue}}
                </mat-option>
            <mat-option  [value]="'disabled'">
                    {{'disabled'}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    

    在你的 ts 文件中

    onChange(data) {
        if(data && data != 'disabled'){
          this.myForm.get('idNum').enable()
        }else{
          this.myForm.get('idNum').disable()
        }
      }
    

    【讨论】:

    • 希望我们有一个可以在 html 本身上完成的单行代码。 .....
    【解决方案2】:

    另一种选择是制定指令

    @Directive({
      selector: '[enableControl]'
    })
    export class EnableControlDirective {
        @Input() set enableControl(condition: boolean) {
            if (this.ngControl) {
                if (this.ngControl.control) {
                    if (condition)
                        this.ngControl.control.enable();
                    else
                        this.ngControl.control.disable();
                }
            }
      }
      constructor(private ngControl : NgControl ) {}
    

    所以你可以像这样使用指令

      <input [enableControl]="condition">
      //e.g.
      <input [enableControl]="myForm.get('IDproof').value">
    

    而且我们不用担心更改、禁用变量等

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 2023-03-08
      • 2021-11-22
      相关资源
      最近更新 更多