根据角度选择组件的值启用或禁用输入字段

时间:2018-10-03 04:43:35

标签: angular angular-material

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

enter image description here

方案::默认情况下,我在此处将输入字段设置为已禁用。如果我从选择中选择某些选项>组件,则该字段变为活动状态。此方案运行正常。

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

这是stackblitz链接。

2 个答案:

答案 0 :(得分:2)

您必须进行一些编辑。在您的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()
    }
  }

答案 1 :(得分:1)

另一种选择是发出指令

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

我们不用担心更改,禁用变量等

相关问题