我的FormGroup带有一些FormControl,并且它们都是必需的,但是我只想在我的component.ts中的布尔值为true时才需要两个FormControles,但我尝试了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>


密码FormControl是我并不总是需要的控件。问题是如果我从密码FormControl中删除了所需的表单本身,而Button似乎无法识别该表单现在又有效了。

最佳答案

对于AngularJs,ng-required是1.x。对于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();

10-08 13:43