有没有办法更新一个FormControl对象Validtors
?我有FormGroup
其中一个输入是一个选择字段,当选择字段的值发生变化时,我希望FormGroup中的其他FormControl更改验证器。角2:更新FormControl验证器后valueChanges
这是我从我的FormGroup组件subscribeToFormChanges()
方法:
private appIdRegexes = {
ios: /^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z0-9\-]+){2,}$/,
android: /^([a-zA-Z])[a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9\-]*){2,}$/,
any: /^any$/
};
private subscribeToFormChanges(): void {
const myFormValueChanges$ = this.appsForm.valueChanges;
myFormValueChanges$.subscribe(x => {
const platform = this.appsForm.controls['platform'].value;
const appId = this.appsForm.controls['appId'].value;
if (this.appIdRegexes[platform]) {
this.appsForm.controls['appId'] = new FormControl(appId, Validators.pattern(this.appIdRegexes[platform].source));
}
});
}
而这里的HTML模板:
<div class="row" [formGroup]="appsForm">
<div class="form-group col-xs-6">
<label>Platform</label>
<select id="licensePlatform" class="form-control"
formControlName="platform">
<option *ngFor="let platform of licensePlatforms" [value]="platform">
{{platform}}
</option>
</select>
<small [hidden]="appsForm.controls.platform.valid">
Platform is required
</small>
</div>
<div class="form-goup col-xs-6">
<label>App ID</label>
<input type="text" class="form-control" formControlName="appId">
<small [hidden]="appsForm.controls.appId.valid">
Please use the right ID format
</small>
</div>
</div>
当我实现subscribeToFormChanges()
方法像这里显示,appsForm.controls.appId.value
不在写入输入字段时再更新。最初价值正在更新。
使用补丁值更新形式this.form.patchValue({controlTobeUpdated:值}); https://angular.io/docs/ts/latest/api/forms/index/FormGroup-class.html#!#patchValue-anchor – Manish
@ user32但是'patchValue()'允许我只更新值 - 不是验证器? –
没错。 patchValue()允许你更新值,但是一旦该值被更新,验证器将被触发。 – Manish