简体   繁体   中英

Angular 2 FormBuilder disable fields on checkbox select

I have build angular cli project and have a form with checkbox. Some of the fields must disable on checkbox select.

Form is as follows 在此输入图像描述

need to disable/enable password, new password and re type password fields on checkbox select event.

Html

<form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

    <div class="row">
        <div class="col">
            <div class="form-group">
                <label> {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['userName']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['displayName']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.EMAIL' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['email']">
            </div>
        </div>
        <div class="col">
            <div class="form-group ">
                <label class="checkbox-inline">
                <input type="checkbox" value="isResetPassword" name="isResetPassword" [formControl]="userProfileForm.controls['isResetPassword']">  
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
              </label>
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['password']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['newPassword']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['reTypePassword']">
            </div>

        </div>

    </div>
</form>

ts code

this.isResetPassword = true;
this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': this.isResetPassword,
    'password': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'newPassword': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'reTypePassword': [{
        value: null,
        disabled: this.isResetPassword
    }]
})

Form has built inside the constructor. How can I disable/enable the above fields on check box select.

At first, I believe that you want to enable fields if and only if isResetPassword checkbox is selected, right? If so, here we go:

1 - The construction of the form should be like this:

this.userProfileForm = this.formBuilder.group({
  // ...
  password: [{
    value: null,
    disabled: !this.isResetPassword
  }],
  newPassword: [{
    value: null,
    disabled: !this.isResetPassword
  }],
  reTypePassword: [{
    value: null,
    disabled: !this.isResetPassword
  }]
});

Note that here I'm disabling inputs only when this.isResetPassword is false.

2 - To detect changes on your <input type="checkbox"> , you can use either (change) in template :

<label>
  <input 
    type="checkbox" 
    [formControl]="userProfileForm.controls['isResetPassword']" 
    (change)="handleChange($event)">
  {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
</label>

... or even, in component , using valueChanges :

this.userProfileForm.get('isResetPassword').valueChanges.subscribe(value => this.handleChange(value));

And, of course, here's the function to manipulate the state of fields.

handleChange(value: boolean): void {
  const passwordCtrl = this.userProfileForm.get('password');
  const newPasswordCtrl = this.userProfileForm.get('newPassword');
  const reTypePasswordCtrl = this.userProfileForm.get('reTypePassword');

  if (value) {
    passwordCtrl.enable();
    newPasswordCtrl.enable();
    reTypePasswordCtrl.enable();
  } else {
    passwordCtrl.disable();
    newPasswordCtrl.disable();
    reTypePasswordCtrl.disable();
  }
}

Some tips:

1 - Although it's only a matter of preference, it's worth to mention that you don't need to use [formControl] like this:

[formControl]="userProfileForm.controls['isResetPassword']"

Instead, you can simply use formControlName :

formControlName="isResetPassword"

Note that you can do the same for all your controls .

2 - You don't need to pass the form value in (ngSubmit) since you've already the reference of userProfileForm in form .

Instead of:

(ngSubmit)="submitForm(userProfileForm.value)"

submitForm(value: any) { console.log(value); }

This:

(ngSubmit)="submitForm()"

submitForm() { console.log(this.userProfileForm.value); }

3 - If you want to see the value of disabled inputs, instead of .value , you should use .getRawValue() , like this:

this.userProfileForm.getRawValue();

DEMO (using (change) )

DEMO (using valueChanges )

The easiest way would be to create a form group just for the passwords:

this.userProfileForm = formBuilder.group({
  'userName': [null, [Validators.required]],
  'displayName': [null],
  'email': [null, [Validators.required]],
  password: formBuilder.group({
    'isResetPassword': this.isResetPassword,
    'password': [null],
    'newPassword': [null],
    'reTypePassword': [null]
  })
})

Then on your template change the passwords col to this:

<div class="col" formGroupName="password>
  <div class="form-group ">
    <label class="checkbox-inline">
      <input type="checkbox" formControlName="isResetPassword">  
      {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
    </label>
  </div>
  <div class="form-group ">
    <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
    <input class="form-control" type="password" formControlName="password" >
  </div>
  <div class="form-group ">
    <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
    <input class="form-control" type="password" formControlName="newPassword">
  </div>
  <div class="form-group ">
    <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
    <input class="form-control" type="password" formControlName="reTypePassword">
  </div>
</div>

on your component:

//when value changes, to disable all the fields just do this
this.userProfileForm.controls.password.disable();
// to enable them back
this.userProfileForm.controls.password.enable();

Most of the methods on this post works but you need to do it with a setTimeout :

setTimeout(() => {
    if (this.disable) {
       this.userProfileForm.controls.password.disable();
    }
    else {
        this.userProfileForm.controls.password.enable();
    }
});

Looks like an Angular bug, issues here and here

Instead of using [formControl] for your controls in the template, use formControlName .

Your form will look like this:

<form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

    <div class="row">
        <div class="col">
            <div class="form-group">
                <label> {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}</label>
                <input class="form-control" type="text" formControlName="userName">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}</label>
                <input class="form-control" type="text" formControlName="displayName">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.EMAIL' | translate }}</label>
                <input class="form-control" type="text" formControlName="email">
            </div>
        </div>
        <div class="col">
            <div class="form-group ">
                <label class="checkbox-inline">
                <input type="checkbox" value="isResetPassword" name="isResetPassword" formControlName="isResetPassword">  
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
              </label>
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
                <input class="form-control" type="password" formControlName="password" [attr.disabled]="userProfileForm.value.isResetPassword?'':null">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" formControlName="newPassword" [attr.disabled]="userProfileForm.value.isResetPassword?'':null">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" formControlName="reTypePassword" [attr.disabled]="userProfileForm.value.isResetPassword?'':null">
            </div>

        </div>

    </div>
</form>

And you have to define your form like this:

this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': [false],
    'password': [null],
    'newPassword': [null],
    'reTypePassword': [null]
})

You need to write a callBack on click of checkbox like (click)="checkBoxClicked()" and in component define callback function as follows

checkBoxClicked() {
 if(!this.userProfileForm.controls.isResetPassword.value) {
   this.userProfileForm.controls.password.disable();
   this.userProfileForm.controls.newPassword.disable();
   this.userProfileForm.controls.reTypePassword.disable();
 }else {
   this.userProfileForm.controls.password.enable();
   this.userProfileForm.controls.newPassword.enable();
   this.userProfileForm.controls.reTypePassword.enable();
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM