需要角度ng

时间:2017-12-27 10:22:59

标签: angular ng-required

我的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>

密码FormControl是控件我不总是希望被要求。问题是,如果我从密码FormControl中删除了表单本身,而Button似乎无法识别该表单现在再次有效。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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();