angular - ngIf 和 formcontrol.touched 不工作

标签 angular validation requiredfieldvalidator angular-forms angular-ng-if

我以前在 Reactive Forms 中做过验证,但从未遇到过这个问题。我在注册表单的电话号码字段上有 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">

关于angular - ngIf 和 formcontrol.touched 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49905166/

相关文章:

validation - 用于验证的 AngularJS 自定义指令 - 输入取决于另一个

jsf-2 - 如何自定义 Primefaces' Growl 所需的验证消息

javascript - Angular 插值无法正常工作?

javascript - Angular2 'this' 未定义

angular - Angular (@angular/localize)是否可以进行运行时语言翻译?

c++ - 如何在 C++ 中使用 std::stoi() 验证 int 输入?

java - 使用注释时如何在 JAXB 解码器上设置自定义 ValidationEventHandler

html - 在 ASP 页面中未触发验证错误消息时隐藏不必要的空间

asp.net-mvc - 验证 mvc 页面中隐藏字段的最佳方法是什么?

node.js - 为什么我必须使用 "npm start x"启动某些脚本,而其他脚本仅使用 "npm x"启动?