簡體   English   中英

Angular Reactive Forms 驗證的奇怪錯誤

[英]Strange errors with Angular Reactive Forms Validation

我正在使用 Angular 7 在我的產品頁面組件表單上測試一個簡單的登錄功能,但我遇到了這種奇怪的行為。 如果存在錯誤,我試圖顯示適當的驗證消息,例如如果它不是有效的電子郵件,則應顯示“必須是有效的電子郵件”消息,如果該字段留空,則“電子郵件是必需的”,應該會顯示錯誤,當您開始輸入時,所需的消息會消失,只顯示有效的電子郵件錯誤消息。 這是我的代碼。

添加product.component.html

所以現在我試圖在錯誤存在但它不起作用時呈現跨度消息。

<form [formGroup]="loginForm" class="login-container" (ngSubmit)="login()">            
    <p>
        <input class="form-control" type="email" placeholder="Email here" formControlName="email">
        <span *ngIf="f.email.errors.required">email is required</span>
        <span *ngIf="f.email.errors.email">must be a valid email</span>
    </p>            
    <p>
        <input class="form-control" type="password" placeholder="Password here" formControlName="password">
        <span *ngIf="f.password.errors.required">Password is required</span>
    </p>
    <p><button type="submit" class="btn btn-md btn-primary">Submit</button></p>        
</form>

添加product.component.ts

這是控制器,我嘗試對驗證規則使用短符號,但無濟於事。

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-addproduct',
  templateUrl: './addproduct.component.html',
  styleUrls: ['./addproduct.component.css']
})
export class AddproductComponent implements OnInit {

  loginForm:FormGroup;
  isSubmitted:boolean = false;

  constructor(
    private router:Router,
    private fb:FormBuilder
  ){}

  ngOnInit() { 
    this.loginForm = this.fb.group({           
      email : ['',  [Validators.required,Validators.email]],    
      password : ['', [Validators.required,Validators.min(6)]]
    });
  }

  get f(){
    return this.loginForm.controls;
  }

}

我也將驗證腳本更改為此但仍然無濟於事

ngOnInit() { 
   this.loginForm = this.fb.group({           
      email : new FormControl('',  [Validators.required,Validators.email]),    
      password : new FormControl('', [Validators.required,Validators.min(6)])
   });
}

我收到這個錯誤

在此處輸入圖片說明

您在可能不存在錯誤的情況下檢查是否存在錯誤。

你想要這樣的東西:

f.email.errors?.required

甚至:

f.email?.errors?.required

對密碼字段和第一次調用時該屬性可能不存在的任何其他地方執行相同的操作。

你也可以使用

<span *ngIf="loginForm.hasError('required', ['password'])">Password is required</span>

在我看來,這要容易得多。

暫無
暫無

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

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