Javascript Angular 2 FormBuilder在复选框选择上禁用字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44969382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:49:32  来源:igfitidea点击:

Angular 2 FormBuilder disable fields on checkbox select

javascriptangularangular2-forms

提问by Janith Widarshana

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

我已经构建了 angular cli 项目并且有一个带有复选框的表单。某些字段必须在复选框选择时禁用。

Form is as follows enter image description here

表格如下 在此处输入图片说明

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

需要在复选框选择事件中禁用/启用密码、新密码和重新输入密码字段。

Html

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.

Form 已经在构造函数内部构建。如何在复选框选择中禁用/启用上述字段。

回答by developer033

At first, I believe that you want to enablefields if and only if isResetPasswordcheckboxis selected, right? If so, here we go:

起初,我相信如果只有选择复选框,则希望启用字段,对右?如果是这样,我们开始:isResetPassword

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

1 - 表格的结构应该是这样的:

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.isResetPasswordis false.

请注意,这里我仅在this.isResetPassword为 false时禁用输入。

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

2 - 要检测对您的更改<input type="checkbox">,您可以(change)模板中使用:

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

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

... 甚至,在component 中,使用valueChanges

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

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

而且,当然,这是function操纵字段状态的方法。

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:

1 - 虽然这只是偏好问题,但值得一提的是,您不需要[formControl]像这样使用:

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

Instead, you can simply use formControlName:

相反,您可以简单地使用formControlName

formControlName="isResetPassword"

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

请注意,您可以对所有控件执行相同操作

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

2 - 您不需要传入表单值(ngSubmit)因为您已经引用了userProfileFormin 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 valueof disabled inputs, instead of .value, you should use .getRawValue(), like this:

3 - 如果您想查看value禁用输入的 ,而不是.value,您应该使用.getRawValue(),如下所示:

this.userProfileForm.getRawValue();


DEMO (using (change))

演示(使用(change)

DEMO (using valueChanges)

演示(使用valueChanges

回答by Fabio Antunes

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:

然后在您的模板上将密码 col 更改为:

<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();

回答by ranbuch

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

这篇文章中的大多数方法都有效,但您需要使用setTimeout

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

Looks like an Angular bug, issues hereand here

看起来像一个 Angular 错误,问题在这里这里

回答by ADreNaLiNe-DJ

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

而不是[formControl]用于模板中的控件,请使用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]
})

回答by Wasif Khan

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

您需要在单击复选框时编写一个(click)="checkBoxClicked()"回调函数,并在组件中定义回调函数,如下所示

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();
 }
}