我有我的 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 中删除所需的表单本身,按钮似乎无法识别表单现在再次有效。