Angular 需要角位移
我的FormGroup中有一些FormControls,所有这些都是必需的,但我希望只有在我的组件中有一个布尔值时才需要两个FormControls。ts是真的,我尝试了Angular 需要角位移,angular,ng-required,Angular,Ng Required,我的FormGroup中有一些FormControls,所有这些都是必需的,但我希望只有在我的组件中有一个布尔值时才需要两个FormControls。ts是真的,我尝试了ng required=“myboolean”,但这不起作用。 有没有办法做到这一点或解决办法 //编辑 onButtonClick() { this.passwordFormControl = !this.passwordFormControl; if(this.passwordFormControl)
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>
onButtonClick()
{
this.passwordFormControl=!this.passwordFormControl;
if(this.passwordFormControl)
{
this.passwortButton=“取消更改密码”;
this.benutzeranalageform.get('password').setValidators(Validators.required);
}
其他的
{
this.passwortButton=“更改密码”;
this.benutzeranalgeform.get('password').clearValidators();
}
}
密码
对于1.x的AngularJs,需要ng。对于Angular或Angular 2+,您可以执行以下操作:
<input [required]="myboolean">
删除:
this.form.get('control-name').clearValidators();
this.form.get('control-name').setValidators(/*Rest of the validators if required*/);
this.form.get('control-name').updateValueAndValidity();
如果我使用第二个建议,我如何删除验证器?所以基本上我必须在点击按钮时设置或删除它。第一次单击时,我将其设置为必需,第二次单击时,我将删除必需的ClearValidators将删除所有验证。然后,您可以再次设置其余的验证,除非您需要tona不工作。。。因此,在开始时,该控件不需要。第一个按钮单击-->控件获取所需属性第二个按钮单击-->控件仍然具有所需属性为什么?能否更新代码以向我展示如何清除验证?此.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();
// 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();