2016-07-07 61 views
1

所以我的问题很简单。当表单从ngModel中获取其值时,我如何在表单上应用验证器。在Angular2表格中应用验证器

所以这是我的组件:

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> 

所以当它加载的观点,我有我的设置形式与用户,但验证不等待新值被设置之前检查!

回答

0

问题出在control.touched条件检查。尝试是这样的:

<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>

+0

古怪,它甚至不使用control.touched工作 – musecz