我正在使用 angular 6 进行开发,我已经实现了如下输入( Angular Material 框架的垫输入),并且我已经将 id 分配给 FormGroup 验证器。当我初始化 typescript 类时,我更新了输入值,但验证器没有看到,当我用 this.formGroup.valid 检查它时,它返回 false,但值是正确的。这是我的代码
constructor(...) {
this.formGroup = formBuilder.group({
id_conto: [Validators.required, Validators.pattern("[0-9]+")],
channel: [Validators.required, Validators.pattern("[0-9]+")],
automatic_size: [],
pip_stoploss: [Validators.required, Validators.pattern("[0-9]+")]
});
this.user = api.getUser();
this.user.subscribe((response) => {
this.userInstance = response;
});
this.editClicked();
}
editClicked() {
if (this.formGroup.valid) {
this.editing = !this.editing;
if (!this.editing)
this.formGroup.disable();
else
this.formGroup.enable();
}
}
还有我的html代码
<mat-form-field class="form-full-width">
<input matInput placeholder="Channel" formControlName="channel"
[errorStateMatcher]="matcher" [value]="userInstance.channel">
<mat-error *ngIf="formGroup.get('channel').hasError('pattern') && !formGroup.get('channel').hasError('require')">
Inserisci un valore numerico
</mat-error>
<mat-error *ngIf="formGroup.get('channel').hasError('require')">
Inserire un valore
</mat-error>
</mat-form-field>
最佳答案
您正在使用响应式表单。要更新表单控件值,请使用表单对象而不是在模板内部执行。
删除:
[value]="userInstance.channel"
相反:
this.user.subscribe((response) => {
this.userInstance = response;
this.formGroup.controls.channel.setValue(this.userInstance.channel);
});
这也应该更新可见值。
关于javascript - Angular 输入更新验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53632857/