簡體   English   中英

在Angular 5中手動設置值后驗證活動表單嗎?

[英]Validating Reactive Form after setting values manually in Angular 5?

當某些事件發生時,我正在手動設置一個反應式表單。 盡管它們沒有通過任何形式的驗證,但它們已更新。

就像

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();

有幾種方法,但我尚未獲得經過驗證的值

我很感謝有人可以以任何方式幫助我,謝謝

編輯:簡單的答案

您可以調用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>

這是一個有效的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM