ngIf 和 formcontrol.touched 不工作

ngIf and formcontrol.touched is not working

我以前在 Reactive Forms 中做过验证,但从未遇到过这个问题。我在注册表单的 phone 数字字段上有 Validators.required。我在模板中使用 formcontrol.invalid 和 formcontrol.touched 属性来捕获错误,但它没有显示错误 div。奇怪的是,如果我删除 formcontrol.touched 然后 formcontrol.invalid 触发。但问题是,当我输入一些数据时,错误 div 仍然可见。

我回到学校看到这个 documentation 但找不到区别。我在我的代码中尝试了不同的文章和实现,但没有任何效果。这在我的代码中可见。

sign-up.component.ts

<form class="form-signup" [formGroup]="form">
    <h1 class="h3 mb-3 font-weight-normal">Please sign up</h1>

    <div class="form-group">
      <label for="inputPhone" class="sr-only">
        Phone Number
      </label>
      <input formContorlName="phoneNumber" type="text" id="inputPhone" class="form-control" placeholder="Phone number" autofocus>
      <div *ngIf="phoneNumber.invalid && (phoneNumber.dirty || phoneNumber.touched)" class="alert alert-danger">
        <div *ngIf="phoneNumber.errors.required">
          Phone number is required.
        </div>
      </div>
    </div>

    <div class="form-group">
      <label for="inputEmail" class="sr-only">
        Email Address
      </label>
      <input formContorlName="emailAddress" type="email" id="inputEmail" class="form-control" placeholder="Email address">
      <div *ngIf="emailAddress.invalid" class="alert alert-danger">Email address is required.</div>
    </div>

    <label for="inputPassword" class="sr-only">
      Password
    </label>
    <input formContorlName="password" type="password" id="inputPassword" class="form-control" placeholder="Password">

    <label for="inputConfirmPassword" class="sr-only">
      Password
    </label>
    <input formContorlName="confirmPassword" type="password" id="inputConfirmPassword" class="form-control" placeholder="Confirm password">

    <div class="checkbox mb-3">
      <label>
        <input type="checkbox" value="remember-me"> Remember me
      </label>
    </div>

    <button class="btn btn-lg btn-primary btn-block" type="submit" (click)="signUp()">
      Sign up
    </button>
    <a routerLink="/signin">Sign in</a>
  </form>

sign-up.component.ts

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

import { SignUpService } from './services/sign-up.service';

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

  form : FormGroup;

  get phoneNumber (){
    return this.form.get('phoneNumber');
  } 
  get emailAddress (){
    return this.form.get('emailAddress');
  } 
  get password (){
    return this.form.get('password');
  } 
  get confirmPassword (){
    return this.form.get('confirmPassword');
  } 

  constructor(
    private _router : Router,
    private _signUpService : SignUpService) { 
    }

  ngOnInit() {
    this.form = new FormGroup({
      'phoneNumber' : new FormControl('', Validators.required),
      'emailAddress' : new FormControl ('', [Validators.required, Validators.email]),
      'password' : new FormControl('', Validators.required),
      'confirmPassword' : new FormControl('', Validators.required),
    });

  }

  signUp(){
    this._signUpService.getAll().subscribe(
      response => {
        console.log(response);
        this._router.navigate(['/signup/otp']);
      }
    );
  }
}

sign-up.module.ts

import { ReactiveFormsModule } from '@angular/forms';
import { OtpCheckerService } from './otp-checker/services/otp-checker.service';
import { SignUpService } from './services/sign-up.service';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SignUpRoutingModule } from './sign-up-routing.module';
import { SignUpComponent } from './sign-up.component';
import { OtpCheckerComponent } from './otp-checker/otp-checker.component';

@NgModule({
  imports: [
    CommonModule,
    SignUpRoutingModule,
    ReactiveFormsModule
  ],
  declarations: [SignUpComponent, OtpCheckerComponent],
  providers:[SignUpService, OtpCheckerService]
})
export class SignUpModule { }

app.module.ts

import { AppErrorHandler } from './common/error-handling/app-error-handler';
import { UserDataService } from './global-services/user-data.service';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule,
    NgbModule.forRoot(),
    ReactiveFormsModule
  ],
  providers: [
    // This service is used for storing and customer related data only.
    UserDataService,
    // Registring global error handler. Also, wherever Angular uses ErrorHandler 
    // it will be replaced by AppErrorHandler
    { provide: ErrorHandler , useClass: AppErrorHandler}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

如果您还需要什么,请告诉我。

更新 1:我在另一个表单上尝试了类似的验证,即我的应用程序中的 otp 检查器表单。这里验证工作正常。 otp 检查表仅在注册模块中。我在上面提供了 sign-up.module.ts 的代码。代码如下

otp-checker.component.html

<form class="form-otpChecker" [formGroup]="form">
    <h1 class="h3 mb-3 font-weight-normal">Please enter otp</h1>
    <div>
        <input 
            formControlName="otp" 
            type="password" 
            id="inputPassword" 
            class="form-control" 
            placeholder="OTP"
            >
        <div *ngIf="otp.invalid && otp.touched" class="alert alert-danger">OTP is required field.</div>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" (click)="submit()">Submit</button>
</form>

otp-checker.component.ts

import { UserDataService } from './../../global-services/user-data.service';
import { OtpCheckerService } from './services/otp-checker.service';
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { User } from '../../entities/user';
import { FormControl, FormGroup, Validators } from '@angular/forms';

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

  private _user: User;

  form : FormGroup;
  get otp (){
    return this.form.get('otp');
  }

  constructor(
    private _router : Router,
    private _userDataService : UserDataService,
    private _otpCheckerService : OtpCheckerService
  ) { 

    this.form = new FormGroup({
      'otp': new FormControl('', Validators.required)
    });
  }
  ngOnInit() {
    this._userDataService.broadCastUser.subscribe(user => this._user = user);
  }

  submit(){
    // TODO : change the hardcoded value as per API response.
    this._otpCheckerService.getAll().subscribe(
      response => {
        console.log(response);
        this._user.isSignedIn = true;
        this._router.navigate(['/checkout']);
      }
    );
  }
}

更新 2 :我什至尝试让注册和 OTP 检查表格几乎完全相同(变量名称不同就是这样)但还是没有变化。

@JBNizet 发现了打字错误。我想我只需要第二只眼睛。错别字在下一行:

<input formContorlName="emailAddress" type="email" id="inputEmail" class="form-control" placeholder="Email address">
               ^^

应该是:

<input formControlName="emailAddress" type="email" id="inputEmail" class="form-control" placeholder="Email address">

你好,我放了一个“?” get函数后签名,例如 *ngIf="!signupForm.get('email')?.valid && signupForm.get('email')?.touched"

我在验证注册表单的字段方面做得很好