>我正在使用Angular Forms处理表单,并且遇到了一个死胡同,只有在第一个输入字段不为空时才想向第二个输入字段添加验证。
假设我有两个输入字段:姓名和年龄。因此,当在名称中键入某些内容时,只有这样年龄才会设置为必需。我正在为我的表单使用 FormGroup 和 FormControl,这就是组件文件现在的样子,没有年龄的验证器:
class Component implements OnChanges {
@Input() name: string;
@Input() age: string;
form = new FormGroup({
name: new FormControl(''),
age: new FormControl('')
});
ngOnChanges(changes) {
if (changes.name?.currentValue !== changes.name?.previousValue) {
this.setName(changes.name.currentValue);
}
if (changes.age?.currentValue !== changes.age?.previousValue) {
this.setAge(changes.age.currentValue);
}
}
setName(name) {
this.form.patchValue({
name,
});
if (name) {
this.form.get('age').setValidators([
Validators.required,
this.form.get('age').validator
]);
}
}
setAge(age) {
this.form.patchValue({
age,
});
}
}
下面是模板:
<custom-input
label="Name"
placeholder="name"
name="name"
formControlName="name"
></custom-input>
<custom-input
label="Age"
placeholder="age"
name="age"
formControlName="age"
></custom-input>
您可以使用以下方法!
收听所需表单字段的更改事件,然后检查字段是否已填充,然后我们可以使用命令切换所需的setValidators
然后在更新后,我们可以通过运行将重新验证表单的updateValueAndValidity
来确保表单同步!
TS
import { Component, OnInit, OnDestroy } from '@angular/core';
import {
FormBuilder,
FormControl,
FormGroup,
Validators,
} from '@angular/forms';
import { Subscription } from 'rxjs';
import { pairwise, startWith } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
name = 'Angular';
form: FormGroup;
subscription: Subscription;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.form = this.formBuilder.group({
control1: [''],
control2: [''],
});
}
control1Change() {
const control1 = <FormControl>this.form.get('control1');
const control2 = <FormControl>this.form.get('control2');
if (control1.value) {
control2.setValidators([Validators.required]);
} else {
control2.setValidators(null);
}
control2.updateValueAndValidity();
}
control2Change() {
const control1 = <FormControl>this.form.get('control1');
const control2 = <FormControl>this.form.get('control2');
if (control2.value) {
control1.setValidators([Validators.required]);
} else {
control1.setValidators(null);
}
control1.updateValueAndValidity();
}
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
.HTML
<hello name="{{ name }}"></hello>
<form [formGroup]="form">
<div style="margin-bottom: 1rem">
<label for="control1">Make Field 2 required</label>
<input
id="control1"
type="text"
formControlName="control1"
(change)="control1Change()"
/>
<span
*ngIf="form.controls.control1.hasError('required')"
style="color: red; display: block; margin-top: 0.25rem;"
>Field 2 is required</span
>
</div>
<div style="margin-bottom: 1rem">
<label for="control2"> Field 2 </label>
<input
id="control2"
type="text"
formControlName="control2"
(change)="control2Change()"
/>
<span
*ngIf="form.controls.control2.hasError('required')"
style="color: red; display: block; margin-top: 0.25rem;"
>Field 2 is required</span
>
</div>
<div>
<button type="submit" [disabled]="!form.valid">
Only enabled when form is valid
</button>
</div>
</form>
分叉堆叠闪电战