这里是一个
complete StackBlitz
具有
反应形式
和
动态验证
.
我们的想法是在
validation
属性,以便在每次设置属性时使用
myControl.setValidators(validate ? [Validators.required] : null)
然后通过调用更新其有效性状态
myControl.updateValueAndValidity()
两种方法对您的
FormControl
在这里:
-
StValueActuffScript()
-
更新值和有效性()
import { Component } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
form: any;
private _validation = true;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
filter: ['Hello'],
filterReason: ['Test'],
documentsRequired: ['Document'],
urgencyReason: ['Nothing'],
reportRequestedDate: [''],
urgencyDate: ['Today'],
urgencyRemarks: ['']
});
this.setValidators(this.validation);
}
set validation(validate: boolean) {
this._validation = validate;
this.setValidators(validate);
}
get validation(): boolean {
return this._validation;
}
setValidators(validate: boolean): void {
this.reportRequestedDate.setValidators(validate ? [Validators.required] : null);
this.reportRequestedDate.updateValueAndValidity();
this.urgencyDate.setValidators(validate ? [Validators.required] : null);
this.reportRequestedDate.updateValueAndValidity();
this.urgencyRemarks.setValidators(validate ? [Validators.required] : null);
this.urgencyRemarks.updateValueAndValidity();
}
onSubmit(): void {
if (this.form.valid) {
console.log(this.form.value);
}
}
get reportRequestedDate(): FormControl {
return this.form.get('reportRequestedDate') as FormControl;
}
get urgencyDate(): FormControl {
return this.form.get('urgencyDate') as FormControl;
}
get urgencyRemarks(): FormControl {
return this.form.get('urgencyRemarks') as FormControl;
}
}
希望有帮助!