To enable or disable the input field based on the

2019-09-04 15:27发布

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

enter image description here

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.

2条回答
ら.Afraid
2楼-- · 2019-09-04 15:41

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

查看更多
ら.Afraid
3楼-- · 2019-09-04 15:44

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()
    }
  }
查看更多
登录 后发表回答