2016-07-07 10 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> 

だから、私は私のフォームはユーザーで設定しましたが、新しい値が前に設定するためにValidatorは待ちません。チェック!

答えて

0

問題はcontrol.touched状態チェックです。それも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

変なふう:このような何かを試してみてください – musecz

関連する問題