1

Onload itself textboxes are disabled mode, if we select checkbox, textboxes should be enabled and uncheck textboxes should be disabled mode and no error borders. I tried below code, validations are working fine but unable to disable/enable checkboxes, please help me the issue..

<input type="checkbox" #chkEnable ngModel />
<label>CheckBox Select to Enable/Disable</label>
<div class="form-group">
    <label>First Name</label>
    <input type="text" [disabled]="!chkEnable.checked" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': ( f.firstName.touched)  && f.firstName.errors }" />
    <div *ngIf="((f.firstName.touched) && f.firstName.errors)" class="invalid-input"></div>
</div>

Demo

2 Answers 2

1

you cannot disable reactive form field from HTML. If you wan to disable reactive from you can use disable() method from reactive form.

After these changes you can disable field.

  1. remove [disabled] property from input.

  2. add (change) event to checkbox

<input type="checkbox" #chkEnable ngModel (change)="disableField(chkEnable.checked)" />

  1. in .ts file create method to disable input

    disableField(checked) { Object.keys(this.f).forEach(key => { if (!checked) { this.f[key].disable(); } else { this.f[key].enable(); } }); }

using this method you can disable all fields in from.

Also if you want to make fields disable on load you can change your form by below code

this.registerForm = this.formBuilder.group({
  firstName: [{ value: "", disabled: true }, Validators.required],
  lastName: [{ value: "", disabled: true }, Validators.required]
});

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

stackoverflow.com/questions/44969382/… In this link you can find other ways to disable input fields
Hi @Kinjal, Could you please suggest me the below question stackoverflow.com/questions/67549092/…
0

we create the change event for checkbox:

<input type="checkbox" (change)="isChecked($event)">
   
isChecked(event){
    let isChecked=event.target.value; 
    if (isChecked) {                         
          this.registerForm.get("firstName").disable();
          this.registerForm.get("lastName").disable();
    } 
    else {
          this.registerForm.get("firstName").enable();
          this.registerForm.get("lastName").enable();
    }
}

I attached the link also https://stackblitz.com/edit/checkbox-to-enable-disable-2bqfkf?file=app/app.component.ts

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.