【问题标题】:Validating Reactive Form after setting values manually in Angular 5?在Angular 5中手动设置值后验证反应形式?
【发布时间】:2018-12-05 04:14:19
【问题描述】:

当某些事件发生时,我手动设置了一个响应式表单。 它们已更新,尽管它们没有通过任何类型的验证。

应该是这样的

this.FORM.controls.WHATEVERINPUT.setValue(X);

关键是我使用的是 Material Design 和 Angular 5,所以在模板中我有这个结构

<mat-form-field>
<input matInput formControlName="WHATEVERINPUT">
<mat-error *ngIf="FORM?.controls.WHATEVERINPUT.errors">
 ... is required & Minimum of 5 characters
</mat-error>
</mat-form-field>

除了我之前提到的那些值之外,它工作得很好。

我已经在控制器中玩过一点

  this.FORM.controls.WHATEVERINPUT.markAsTouched();
    this.FORM.controls.WHATEVERINPUT.markAsDirty();
    this.FORM.updateValueAndValidity();

通过多种方式,但我还没有获得值验证

如果有人能以任何方式帮助我,我将不胜感激 谢谢

【问题讨论】:

  • 你能发布你的组件的打字稿代码吗?你如何创建你的控制器,你使用的是哪种Validators

标签: angular angular-material material-design angular5 angular-reactive-forms


【解决方案1】:

编辑:简单回答

设置值后可以调用this.form.get('username').markAsTouched();

另一个答案

如果你把你的按钮放在表单中,添加一个(ngSubmit)="USR($event)"作为你的表单标签的属性,然后在你的按钮上添加type="submit",你会让Angular检测表单是否有效,然后是错误将显示消息。

<form class="example-form" [formGroup]="form" (ngSubmit)=USR($event)>
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Username" formControlName="username">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <input matInput placeholder="Password" formControlName="password">
  </mat-form-field>

  <button mat-raised-button type="button" color="primary" [style.margin]="'12px'" (click)="PWD()">Update password with value</button>
  <button type="submit" mat-raised-button color="primary" [style.margin]="'12px'">Update username required error</button>
</form>

Here is a working example

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2019-04-28
    • 2018-07-19
    • 2018-10-10
    • 2019-09-11
    • 2018-03-21
    • 2017-06-03
    • 2022-01-26
    • 2018-09-22
    相关资源
    最近更新 更多