Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 将验证器中的字段与angular2进行比较_Typescript_Angular - Fatal编程技术网

Typescript 将验证器中的字段与angular2进行比较

Typescript 将验证器中的字段与angular2进行比较,typescript,angular,Typescript,Angular,我正在尝试用Angular2创建一个注册表,具有“重复密码”功能。我希望使用自定义验证器作为表单控件来实现这一点 我遇到的问题是,当验证器运行时,“此上下文”似乎被设置为验证器,因此我无法访问RegistrationForm类上的任何本地方法。我似乎找不到任何好方法从验证器访问控制组 有人知道在自定义验证器中访问同一控制组中的其他控件的好方法吗 以下是组件的简短示例: import { Component, View } from 'angular2/angular2'; import { Va

我正在尝试用Angular2创建一个注册表,具有“重复密码”功能。我希望使用自定义验证器作为表单控件来实现这一点

我遇到的问题是,当验证器运行时,“此上下文”似乎被设置为验证器,因此我无法访问RegistrationForm类上的任何本地方法。我似乎找不到任何好方法从验证器访问控制组

有人知道在自定义验证器中访问同一控制组中的其他控件的好方法吗

以下是组件的简短示例:

import { Component, View } from 'angular2/angular2';
import { Validators, ControlGroup, Control, FORM_DIRECTIVES, FORM_BINDINGS } from 'angular2/angular2';

@Component({
    selector: 'form-registration'
})
@View({
    directives: [FORM_DIRECTIVES, ROUTER_DIRECTIVES],
    template: `
        <form (submit)="register($event)" [ng-form-model]="registerForm">
            <label for="password1">Password:</label>
            <input id="password1" ng-control="password1" type="password" placeholder="Passord" />

            <label for="password2">Repeat password:</label>
            <input id="password2" ng-control="password2" type="password" placeholder="Gjenta passord" />

            <button class="knapp-submit" type="submit" [disabled]="!registerForm.valid">Registrer deg</button>
        </form>
    `
})
export class RegistrationForm {
    registerForm: ControlGroup;

    constructor() {            
        this.registerForm = new ControlGroup({
            password1: new Control('', Validators.required),
            password2: new Control('', this.customValidator)
        });
    }

    public register(event: Event) {
        // submit form
    }

    private customValidator(control: Control) {
        // check if control is equal to the password1 control
        return {isEqual: control.value === this.registerForm.controls['password1'].value};
    }
}
从'angular2/angular2'导入{组件,视图};
从'angular2/angular2'导入{验证器、控制组、控件、表单_指令、表单_绑定};
@组成部分({
选择器:“表单注册”
})
@看法({
指令:[形式指令,路由器指令],
模板:`
密码:
重复密码:
登记者度
`
})
出口类登记表{
注册执行者:对照组;
构造函数(){
this.registerForm=新控制组({
密码1:新控件(“”,需要验证程序),
密码2:新控件(“”,this.customValidator)
});
}
公众登记册(事件:事件){
//提交表格
}
专用customValidator(控件:控件){
//检查控件是否等于password1控件
返回{isEqual:control.value==this.registerForm.controls['password1'].value};
}
}

所以我通过将customValidator绑定到我的类的这个上下文中解决了这个问题,正如Sergio在评论中解释的那样

请记住,.bind(this)函数返回具有绑定上下文的函数的新实例

import { Component, View } from 'angular2/angular2';
import { Validators, ControlGroup, Control, FORM_DIRECTIVES, FORM_BINDINGS } from 'angular2/angular2';

@Component({
    selector: 'form-registration'
})
@View({
    directives: [FORM_DIRECTIVES, ROUTER_DIRECTIVES],
    template: `...my form template...`
})
export class RegistrationForm {
    registerForm: ControlGroup;

    constructor() {           
        this.customValidator = this.customValidator.bind(this); 
        this.registerForm = new ControlGroup({
            password1: new Control('', Validators.required),
            password2: new Control('', this.customValidator)
        });
    }

    public register(event: Event) {
        // submit form
    }

    private customValidator(control: Control) {
        // check if control is equal to the password1 control
        return {isEqual: control.value === this.registerForm.controls['password1'].value};
    }
}

尝试使用此代码进行验证。它成功地工作了

Register.component.html
}

您是否尝试过使用
this.customValidator.bind(this)
(我想这就是语法)。另一种方法可以是匿名函数:
新控件(“”,()=>{})
(胖箭头有助于解决我所看到的上下文问题)@EricMartinez this.customValidator.bind(这个)对我来说非常好用。干杯对我来说也很好。如果您将其添加为答案,我可以将其设置为已接受:)@Etse,您可以向您展示
this.customValidator.bind(this)
如何工作的代码吗?仍然会收到一条错误消息:异常:RegisterPage实例化期间出错!。
<div class="signin-content">
    <mat-card>
      <mat-card-content>
        <form [formGroup]="userForm1" (ngSubmit)="onSubmit()">
          <p>Please Register Here</p>
          <mat-input-container class="full-width-input">
            <input matInput placeholder=" First Name" formControlName="firstname" >
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput  placeholder="Last Name"   formControlName="lastname" >
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput placeholder="Phone No."   formControlName="phone" required>
            <div *ngIf="userForm1.controls['phone'].hasError('pattern')" class="alert alert-danger" >
                please Enter 10 digits....
            </div>
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput  placeholder="E-mail"   formControlName="email"  required>
            <span *ngIf="userForm1.hasError('email', 'email') && userForm1.get('email').touched" class="alert-danger">
                Please enter valid email contains '@','.' ...
              </span>
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput type="password" placeholder="Password"   formControlName="password" required >
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput type="password" placeholder="Confirm Password"   formControlName="cpassword" required>
            <div  *ngIf="userForm1.controls['cpassword'].errors?.MatchPassword && userForm1.get('cpassword').touched " class="alert alert-danger">
                Password not match
            </div>
          </mat-input-container>
          <button mat-raised-button [disabled]="!userForm1.valid" color="primary" type="submit">Register</button>

        </form>
      </mat-card-content>
    </mat-card>
  </div>
import { Component, OnInit, Output, EventEmitter, ViewChild } from '@angular/core';

import { MatGridListModule, MatButtonModule, MatInputModule, MatDialog,MatDialogRef } from '@angular/material';

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

import {HttpClient} from '@angular/common/http';

import { Router } from '@angular/router'

import 'rxjs/add/operator/map';

import { Headers, Http, RequestOptions } from '@angular/http';

import { EqualTextValidator } from "angular2-text-equality-validator";

import { PasswordValidation } from './Passwordvalidation';

@Component({

  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']

})

export class RegistrationComponent implements OnInit {

  userForm1:FormGroup;
  password = 'password';

  constructor( private _formBuilder: FormBuilder,
    // public thisDialogref: MatDialogRef<AppComponent>  ,
    private http:HttpClient,
    private router: Router){}

  ngOnInit() {

    this.userForm1=this._formBuilder.group({

      id:[""],
      firstname:[""],
      lastname: [""],
      phone:[null,[Validators.required, Validators.pattern('^[1-9][0-9]{9}$'),Validators.maxLength(10)]],

      email:[null,[Validators.required,Validators.email]],
      password:["",[Validators.compose([Validators.required])]],
      cpassword:["",[Validators.required]],
      createdDate:[""],
      updatedDate:[""],
      status:[""]
    },{
      validator: PasswordValidation.MatchPassword // your validation method
    })
  }

  onSubmit(){
    console.log(this.userForm1.value);
    this.http.post("http://localhost:4001/user/signup",this.userForm1.value).subscribe(result => {
      console.log("register successful");
     });
     this.router.navigate(['/login']);
  }

}
static MatchPassword(AC: AbstractControl) {
   let password = AC.get('password').value; // to get value in input tag
   let cpassword = AC.get('cpassword').value; // to get value in input tag
    if(password != cpassword) {
        console.log('false');
        AC.get('cpassword').setErrors( {MatchPassword: true} )
    } else {
        console.log('true');
        return null
    }
}