Angular ng-required

Kai*_*Kai 3 ng-required angular

我有我的 FormGroup 和一些 FormControles 并且所有这些都是必需的,但我希望只有当我的 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>
Run Code Online (Sandbox Code Playgroud)

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

Vin*_*ani 7

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

<input [required]="myboolean">
Run Code Online (Sandbox Code Playgroud)

当布尔值发生变化时,您也可以在 component.ts 中动态执行此操作,如下所示:

this.form.get('control-name').setValidators(Validators.required);
this.form.get('control-name').updateValueAndValidity();
Run Code Online (Sandbox Code Playgroud)

去除:

this.form.get('control-name').clearValidators();
this.form.get('control-name').setValidators(/*Rest of the validators if required*/);
this.form.get('control-name').updateValueAndValidity();
Run Code Online (Sandbox Code Playgroud)