3

我的 FormGroup 有一些 FormControles,它们都是必需的,但我希望我的两个 FormControles 仅在我的 component.ts 中的布尔值是 true 时才需要,我试过了ng-required="myboolean",但这没有用。有没有办法做到这一点或解决方法?

//编辑

onButtonClick()
  {
    this.passwordFormControl = !this.passwordFormControl;

    if(this.passwordFormControl)
    {
      this.passwortButton = "Cancle change Password";
      this.benutzerAnlageForm.get('password').setValidators(Validators.required);
    }
    else
    {
      this.passwortButton = "Change password";
      this.benutzerAnlageForm.get('password').clearValidators();
    }
  }

 <form [formGroup]="MyForm" (ngSubmit)="onMyForm()">

  <div *ngIf="passwordFormControl" class = "form-group">
      <label for="password">Password</label>
      <input formControlName="password" type="password" id="password" 

 <-- Some more Form Controles that are always required -->

  <button type="submit" [disabled]="!MyForm.valid" class ="btn btn-primary">Save</button>
  <button *ngIf="edit" type="button" class="btn btn-primary" (click)="onButtonClick()">{{passwortButton}}</button>
  </form>

Password FormControl 是我不总是需要的控件。问题是,如果我从密码 FormControl 中删除所需的表单本身,并且按钮似乎无法识别表单现在再次有效。

4

2 回答 2

7

ng-required 用于 1.x 的 AngularJs。对于 Angular 或 Angular 2+ 你可以这样做:

<input [required]="myboolean">

当您的布尔值更改时,您也可以在 component.ts 中动态执行此操作,如下所示:

this.form.get('control-name').setValidators(Validators.required);
this.form.get('control-name').updateValueAndValidity();

去除:

this.form.get('control-name').clearValidators();
this.form.get('control-name').setValidators(/*Rest of the validators if required*/);
this.form.get('control-name').updateValueAndValidity();
于 2017-12-27T10:34:32.517 回答
0
// To add validation     
   this.myForm.controls.controlName.setValidators(Validators.required);

// To clear validation
   this.updateForm.controls.controlName.clearValidators();

// In either case, call this method
   this.updateForm.controls.controlName.updateValueAndValidity();
于 2019-06-17T07:48:32.207 回答