To enable or disable the input field based on the value of select component in angular

耗尽温柔 提交于 2020-01-06 04:44:05

问题


I am having 2 component select and input component.as shown in below image.

Scenario: Here by default i have set input field as disabled.If i choose some option from select component then the field becomes active.This scenario is working fine.

Expected Result: I should have another option in the select component(i,e dropdown) to disable the input field again(If user doesn't want want choose anything from select component).

Here is the stackblitz link.


回答1:


You have to do some editings. in your Html file

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

And in your ts file

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



回答2:


Another option is make a directive

@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 ) {}

So you can use the directive like

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

and we don't worry about changes, disables variables, etc



来源:https://stackoverflow.com/questions/52619826/to-enable-or-disable-the-input-field-based-on-the-value-of-select-component-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!