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