【发布时间】:2020-01-03 13:19:25
【问题描述】:
我正在尝试创建一个仅对四个字段中的两个字段进行验证的表单,因此在切换表单时尝试为每个字段添加和删除验证器。任何帮助将不胜感激,因为我认为我错过了一些非常小的东西。
你可以在这里下载 repo - https://github.com/1Guv/ths-reactive-forms
这是我的组件:
ngOnInit() {
this.familyForm = this.parentForm.form;
this.addFormControls();
}
toggle() {
this.switch = !this.switch;
this.addFormControls();
}
addFormControls() {
// this.familyForm.clearValidators();
if (!this.switch) {
console.log('Father & Mother');
this.familyForm.addControl('family', new FormGroup({
fatherName: new FormControl('', [Validators.required]),
motherName: new FormControl('', [Validators.required]),
uncleName: new FormControl(''),
auntieName: new FormControl('')
}))
} else {
console.log('Uncle & Auntie');
this.familyForm.addControl('family', new FormGroup({
fatherName: new FormControl(''),
motherName: new FormControl(''),
uncleName: new FormControl('', [Validators.required]),
auntieName: new FormControl('', [Validators.required])
}))
}
this.familyForm.updateValueAndValidity();
console.log('form controls', this.familyForm.controls);
}
这是我的html:
<h6>Family Form Component</h6>
<div formGroupName="family">
<h6 *ngIf="!switch">Father & Mother</h6>
<div *ngIf="!switch" class="row">
<br>
<div class="col">
<mat-form-field appearance="fill">
<mat-label>Father name</mat-label>
<input matInput type="text" formControlName="fatherName" class="form-control" placeholder="Father name">
</mat-form-field>
</div>
<div class="col">
<mat-form-field appearance="fill">
<mat-label>Mother name</mat-label>
<input matInput type="text" class="form-control" placeholder="Mother Name" formControlName="motherName" >
</mat-form-field>
</div>
</div>
<div>
<h6 *ngIf="switch">Uncle & Auntie</h6>
<div *ngIf="switch" class="row">
<br>
<div class="col">
<mat-form-field appearance="fill">
<mat-label>Uncle name</mat-label>
<input matInput type="text" formControlName="uncleName" class="form-control" placeholder="Uncle name">
</mat-form-field>
</div>
<div class="col">
<mat-form-field appearance="fill">
<mat-label>Auntie name</mat-label>
<input matInput type="text" class="form-control" placeholder="Auntie Name" formControlName="auntieName" >
</mat-form-field>
</div>
</div>`enter code here`
</div>
<button type="button" class="m-4" mat-raised-button (click)="toggle()">Switch</button>
【问题讨论】:
标签: angular validation reactive