简体   繁体   English

在Angular2表单中应用验证器

[英]Apply Validators in an Angular2 Form

So my question is pretty simple. 所以我的问题非常简单。 How can I apply validators on a Form when the form fetch his value from ngModel. 当表单从ngModel获取其值时,如何在表单上应用验证器。

So this is my component: 所以这是我的组成部分:

constructor(private _fb ? : FormBuilder,
  private _router ? : Router,
  private _usersService ? : UsersService,
  private _route ? : ActivatedRoute) {}


ngOnInit() {
  // Fetch the Id when Editing the User
  this.sub = this._route.params.subscribe(params => {
    let id = params['id'];
    this.title = id ? "Edit User" : "New User";
    if (!id)
      return;

    this._usersService.getUser(id)
      .subscribe(
        user => this.user = user,
        response => {
          if (response.status == 404)
            this._router.navigateByUrl("/NotFound");
        }
      )
  });
}

ngAfterContentInit() {
  // Let's define the form group
  this.form = this._fb.group({
    name: ['', Validators.compose(
      [Validators.required, Name.cannotContainSpace]
    ), Name.shouldBeUnique],
    email: ['', Validators.compose(
      [Validators.required, Email.shouldBeAnEmail]
    )],
    phone: ['', Validators.compose(
      [Validators.pattern("[0-9]{5,10}"), Validators.required]
    )],
  });
}

ngAfterViewInit() {
  // Component views are initialized
  // I probably could Apply my validators in this hook cycle.
}

ngOnDestroy() {
  this.sub.unsubscribe();
}
<!-- Just put an example for the form-control -->
<input [(ngModel)]="user.name" type="text" class="form-control" id="inputName" placeholder="Name" ngControl="name" #name="ngForm">
<div *ngIf="name.control.pending">
  searching for uniqueness...
  <i class="fa fa-spinner fa-spin fa-1x"></i>
</div>
<div *ngIf="name.touched && name.errors">
  <div *ngIf="name.errors.required" class="alert alert-danger">Name is required</div>
  <div *ngIf="name.errors.cannotContainSpace" class="alert alert-danger">Name cannot contain space</div>
  <div *ngIf="name.errors.shouldBeUnique" class="alert alert-danger">Name should be unique</div>
</div>

So when It loads the view, I got my form set with the user but the Validator doesn't wait for the new value to be set before checking ! 因此,当它加载视图时,我得到了用户的表单集,但Validator不会等待在检查之前设置新值!

Problem is with control.touched condition checking. 问题在于control.touched条件检查。 Try something like this : 尝试这样的事情:

 <div *ngIf="name.valid"> <div *ngIf="name.hasError('required')" class="alert alert-danger">Name is required</div> <div *ngIf="name.hasError('cannotContainSpace')" class="alert alert-danger">Name cannot contain space</div> <div *ngIf="name.hasError('shouldBeUnique')" class="alert alert-danger">Name should be unique</div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM