一个angular4.0响应式表单应用~~~

来源:互联网 发布:nginx apache php性能 编辑:程序博客网 时间:2024/06/05 05:22

效果图,待解决的bug

这是之前说的要写的那个网站。。还在慢慢慢慢慢完善。。。如图效果有一点磕碜。。。。但是功能还是有的,目前有一个我无法解决的bug,在验证码哪里,少位或者多位都会有错误提示(除了其他的还有提示验证码不匹配),bug就是假如我输入四个数字(和给定的验证码不一样),这个不匹配的错误提示就没了,,但是我在提交的时候就会显示我的验证码和给定的不匹配(因为他没有弹出alert,证明输入有问题)!!很奇怪,,,如果有伙伴运行的话。。。能找出来错在哪的话。。。请指教^_^
这里写图片描述

这里写图片描述

这里写图片描述
~~~叮叮叮贴代码

user.component.html

<div class="container">  <div class="loginInBox row">    <form [formGroup] = "login" #formDir="ngForm" class="col-md-12" (submit)="onSubmit()" novalidate>      <div class="form-group">        <div class="lineBottom">          <label><span>用户名:</span> </label>          <input type="text"  class="addPadding form-control"  formControlName="username"/>          <div [hidden]="login.get('username').valid || login.get('username').untouched" class="alert alert-danger">            <div [hidden]="!login.hasError('required', 'username')">              请输入用户名            </div>            <div [hidden]="!login.hasError('minlength', 'username')">              用户名不少于两个字            </div>            <div [hidden]="!login.hasError('maxlength', 'username')">              用户名不多余6个字            </div>          </div>        </div>        <div class="lineBottom">          <label>密<span style="padding: 10px"></span>码:</label>          <input type="password" class="addPadding form-control" formControlName="password">          <div [hidden] = "login.get('password').valid || login.get('password').untouched" class="alert alert-danger">            <div [hidden] = "!login.hasError('required', 'password')">              密码不能为空            </div>            <div [hidden] = "!login.hasError('minlength', 'password')">              密码不能少于六位            </div>          </div>        </div>        <div class="lineBottom" formGroupName="checkCode" style="border: none">          <label class="floatLeft">验证码:</label>          <input type="text" class="addPadding form-control" formControlName="userInputCode" [(ngModel)] = "userInputCode" style="width: 180px;">          <div class="checkNum checkDiv">            <div class="checkNum" formGroupName="ranCode">              <input class="checkNumLi" formControlName="ranFirstCode"  readonly>              <input class="checkNumLi" formControlName="ranSecondCode" readonly>              <input class="checkNumLi" formControlName="ranThirdCode" readonly>              <input class="checkNumLi" formControlName="ranForthCode" readonly>            </div>          </div>          <div [hidden] = "login.get('checkCode').get('userInputCode').valid  || login.get('checkCode').get('userInputCode').untouched" class="alert alert-danger">            <div [hidden] = "! login.hasError('required', ['checkCode', 'userInputCode'])">              请输入验证码            </div>            <div [hidden] = "! login.hasError('minlength', ['checkCode', 'userInputCode'])">              请输入四位数字验证码            </div>            <div [hidden] = "! login.hasError('maxlength', ['checkCode', 'userInputCode'])">              请输入四位数字验证码            </div>            <div [hidden] = "! login.hasError('pattern', ['checkCode', 'userInputCode'])">              输入的验证码类型不对,请输入数字!            </div>            <div [hidden] = "! login.hasError('equals', ['checkCode'])">              验证码不匹配,请重新填写~            </div>          </div>        </div>      <div class="btnDiv">        <button class="btn btn-warning"  type="submit">登录</button>        <button class="btn btn-warning">没有账号,注册一个噻</button>        <button [routerLink] = "['']" class="btn btn-warning">返回</button>        <button class="btn btn-danger chooseLoginWay" (mouseover)="ShowLoginInWay()" (mouseleave)="hideLogInWay()" >选择其他方式登录</button>        <div *ngIf="isShowLoginInWay"  class="imgUl" (mouseover)="show()" (mouseleave)="hide()">          <ul>            <li *ngIf = "result">                <img src="../../assets/images/chat.jpg" width = "100" height="100"> </li>            <li *ngIf = "result">              <img src="../../assets/images/qq.png" width = "100" height="100"></li>          </ul>        </div>      </div>      </div>    </form>  </div></div>

user.component.css

.container{  font-family: "Arial Black";  font-size: 15px;  color: teal;  width:500px;  height: auto;  /*border:1px solid crimson;*/  /*background-color: teal;*/}.loginInBox{  width:490px;  height: inherit;  /*border:1px solid salmon;*/}li{  list-style: none;}.addPadding{  display: inline-block;  /*margin-left: 40px;*/  padding-left: 15px;  width:380px;  height:35px;  border: 1px solid yellowgreen;  -webkit-border-radius: 15px;  -moz-border-radius: 15px;  border-radius: 15px;}.lineBottom{  margin-bottom:20px;}button{  background-color: transparent;}.checkDiv{  width:142px;  height:auto;  margin-left: 20px;}.checkNum{  display: inline-block;  width:140px;  height:42px;  /*border: 1px solid hotpink;*/}.checkNumLi{  display: inline-block;  width:30px;  height:40px;  /*border: 1px solid hotpink;*/  background-image:  url('../../assets/images/ML-2017100919_sh3900_P.jpg');}.btnDiv{  width:485px;  height:auto;}.btnDiv button {  display: block;  width:450px;  height:30px;}.checkNum li:nth-child(1){  /*margin-top: 10px;*/}.checkNum li:nth-child(2){  border:1px solid red;}.ng-valid[required], .ng-valid.required  {  border-left: 5px solid #42A948; /* green */}.ng-invalid:not(form)  {  border-left: 5px solid #a94442; /* red */}.chooseLoginWay{  position: relative;}.imgUl{  display: inline-block;  position: absolute;  margin-left: -20px;  z-index: 2;  border:1px solid palevioletred;  box-shadow: 2px  3px 20px   rgba(28,15,21,0.9);  width:205px;  height:105px;}img{ float: left;}.btn{  color: teal;  transition: color 0.5s;}.btn:hover{  color: #EDEDED;}.showPwd{  cursor: pointer;}

user.component.ts

import {Component, EventEmitter, Injectable, OnInit, Output} from '@angular/core';import {ActivatedRoute} from '@angular/router';import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';import {validate} from "codelyzer/walkerFactory/walkerFn";@Component({  selector: 'app-user',  templateUrl: './user.component.html',  styleUrls: ['./user.component.css']})@Injectable()export class UserComponent implements OnInit {  @Output()    rannums: Array<number>;  login: FormGroup;  public isShowLoginInWay: boolean = false;  public result: boolean;  public userInputCode: string;  checkEqualValidator (group: FormGroup):  any {    let result : boolean = false;    let  userInput : FormControl = group.get('userInputCode') as FormControl;    const userInputValue = userInput.value;    let firstc : FormControl = group.get('ranCode').get('ranFirstCode') as FormControl;    let  secondc : FormControl = group.get('ranCode').get('ranSecondCode') as FormControl;    let  thirdc : FormControl = group.get('ranCode').get('ranThirdCode') as FormControl;    let  forthc : FormControl = group.get('ranCode').get('ranForthCode') as FormControl;    let  codeArr = [];    codeArr[0] = firstc.value;    codeArr[1] = secondc.value;    codeArr[2] = thirdc.value;    codeArr[3] = forthc.value;    if(userInputValue) {    //  这里加个判断是因为,初进入页面用户输入这个input没有值,    // 但是里面有用到(eg. userInputValue[0])这时就会报错,很不美丽,    // 所以等这个input有值了在进行判断      console.log('0: ' + userInputValue[0] ==codeArr[0] );      console.log('userInputValue[0]: ' + userInputValue[0]  );      if ( (userInputValue[0] == codeArr[0] && userInputValue[1] == codeArr[1] && userInputValue[2] == codeArr[2]          && userInputValue[3] == codeArr[3])) {          //  判断用户输入的数字是否与给定的数字一一对应,如果相等则返回null,          // 我们知道如果校验器返回null的话,错误提示是不会出现的,证明用户输入的信息无误。        console.log("用户输入与给定验证码匹配");        return null;      }      else {        console.log("用户输入与给定验证码不不不不不不不不不不不匹配");        return {equals: true}        // 如果有一个数字不相等则返回一个对象,此时错误提示会出现,说明用户输入的消息有误。      }    }    else {      return {equals: true}    }  }  constructor(fb: FormBuilder) {  // 构建表单的结构    this.login = fb.group({      'username':  ['', [Validators.required,  Validators.minLength(2),  Validators.maxLength(6)]],      'password': ['', [ Validators.required, Validators.minLength(6)]],      'checkCode': fb.group({        'userInputCode': ['', [ Validators.required, Validators.minLength(4), Validators.maxLength(4), Validators.pattern(/[0-9]/)]],        'ranCode': fb.group({          // 随机产生验证码,我把用户输入验证码和随机产生验证码放在了一个formGroup里了。        // 第一个参数是一个产生随机数的函数          'ranFirstCode': [this.createRandomNums(),[]],          'ranSecondCode': [this.createRandomNums(),[]],          'ranThirdCode': [this.createRandomNums(),[]],          'ranForthCode': [this.createRandomNums(),[]]        })      }, {validator: this.checkEqualValidator})      // 自定义的校验器,校验用户输入的数字和给定的是否一样    });  }  ngOnInit() {  }  onSubmit(){    if(this.login.valid) {    // 若整个表单都合法,则提交的时候显示alert内容      alert("所有消息都合法~");    }  } ShowLoginInWay() { // 当焦点停留在<button >选择其他方式登录</button>按钮上,触发此函数,显示两张二维码图片    this.isShowLoginInWay = true;    this.result = true;  }  hideLogInWay () {  // 鼠标焦点离开时,隐藏二维码图片    this.isShowLoginInWay = false;    this.result = false;  }  createRandomNums () {  // 产生随机数    return Math.floor(Math.random() * 10);  }  show () {    this.result = true;    this.isShowLoginInWay = true;  }  hide () {    this.result = false;    this.isShowLoginInWay = false;  }}

说一下我踩到的坑。。。

自定义校验器那里!!!返回的对象属性名称千万不要是保留的字符串,我最初属性名是equal,然后错误提示消息怎样都不现实,一度以为浏览器出问题了。。。。最后改成equals就好了

一点点重要。。。

如果校验器返回null的话,错误提示是不会出现的,证明用户输入的信息无误。
如果校验器返回一个对象,此时错误提示会出现,说明用户输入的消息有误。