【发布时间】:2017-02-15 07:34:40
【问题描述】:
有没有办法更新 FormControl 对象的Validtors? I have FormGroup where one Input is a select field, when the value of the select field changes I want the other FormControl in my FormGroup to change the validator.
这是我的 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:value}); angular.io/docs/ts/latest/api/forms/index/…
-
@user32 但
patchValue()只允许我更新值 - 而不是验证器? -
对。 patchValue() 允许你更新值,但是一旦该值被更新,验证器就会被触发。
-
现在我明白你的问题了,我在建议别的东西。
标签: javascript angular typescript