2016-12-16 20 views
7

Tôi đang sử dụng ReactiveFormsModule và đã định nghĩa tất cả các điều khiển biểu mẫu của tôi bao gồm các trình xác nhận đơn giản như Validators.required trong cấu hình const.Làm thế nào để thêm một Validator động vào FormControl trong Angular 2

Tôi muốn thêm trình xác thực tùy chỉnh vào một trong các FormControls đó.

Tôi hiện đã thêm trình xác thực tùy chỉnh làm chức năng trong cấu hình này và nó hoạt động tốt, nhưng không thuộc về nó, nó thực sự cần phải sống trong thành phần của tôi, nhưng tôi không chắc chắn đính kèm trình xác thực tùy chỉnh theo cách thủ công sau khi FormBuilder đã định cấu hình tất cả các điều khiển của tôi.

Xem Mã Comment dưới đây trông như thế này

Làm thế nào để Đính kèm đây

* ??? *

this.form.get ('site_id'). Thêm tùy chỉnh valiator

Đây là mã cấu hình hiện tại của tôi.

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

var fb = new FormBuilder(); 

function exampleValidator(control: FormControl): { [s: string]: boolean} { 
    if (control.value === 'Example'){ 
     return { example: true }; 
    } 

    return null; 
} 

export const formConfig = fb.group({ 
    'extract_batch_id': ['bbbbbbbbbbbbb', 
    [ 
     Validators.required 
    ]], 
    'site_id': ['blah', 
    [ 
     Validators.required, 
     exampleValidator 
    ]] 
}); 

Tôi có một chỉ thị mà thực sự nên được lưu trữ các validator tùy chỉnh

Job Search Component

import {Component, Input, OnInit, OnDestroy} from '@angular/core'; 
import {FormGroup, FormControl} from '@angular/forms'; 
import {ActivatedRoute} from '@angular/router'; 
import {Subscription} from 'rxjs'; 

import {Job} from '../../../models/job'; 
import {JobService} from '../../../services/api/job.service'; 
import {DebugService} from '../../../common/debug/debug.service'; 
import {formConfig} from './edit.form-config'; 

@Component({ 
    selector: 'wk-job-search-edit', 
    template: require('./edit.html') 
}) 
export class JobSearchEditComponent { 
    form: FormGroup; 

    job: Job; 

    @Input() jobId: number; 
    private subscription: Subscription; 

    constructor(
     private route: ActivatedRoute, 
     private jobService: JobService, 
     private debug: DebugService){ 

     // Configure form FormGroup via exported formConfig 
     this.form = formConfig; 

     // How do I Attach Here 
     // *** ??? *** 
     // this.form.get('site_id').add custom valiator 
    } 

    /* 
    exampleValidator(control: FormControl): { [s: string]: boolean} { 
     if (control.value === 'Example'){ 
      return { example: true }; 
     } 

     return null; 
    } 
    */ 
} 

jobsearch Edit.html

<form [formGroup]="form" (ngSubmit)="onSubmit()"> 

    <button type="submit" class="btn btn-success" [disabled]="!form.valid">Save</button> 
    <div class="form-group" [ngClass]="{'has-danger':!form.get('extract_batch_id').valid}"> 
     <label for="extract_batch_id" class="form-control-label">Extract Batch</label> 
     <input id="extract_batch_id" formControlName="extract_batch_id" type="text" placeholder="Extract Batch" class="form-control input-sm"> 
     <div *ngIf="!form.get('extract_batch_id').valid"> 
      <div class="form-control-feedback">Extract Batch is required?</div> 
      <small class="form-text text-muted">Please enter a Extract Batch, eg. xyz.</small> 
     </div> 
    </div> 

    <div class="form-group" [ngClass]="{'has-danger':!form.get('site_id').valid}"> 
     <label for="site_id" class="form-control-label">Site</label> 
     <input id="site_id" formControlName="site_id" type="text" placeholder="Site" class="form-control input-sm"> 
     <div *ngIf="!form.get('site_id').valid"> 
      <div class="form-control-feedback">Site is required?</div> 
      <small class="form-text text-muted">Please enter a Site, eg. xyz.</small> 
     </div> 
    </div> 


</form> 
+0

Bạn có thể xin vui lòng đặt tập tin html JobSearchEditComponent của bạn, – Milad

+0

Tôi đã thêm HTML –

Trả lời

13

Nhìn vào mã của bạn, những gì bạn có thể làm:

<div class="form-group" [ngClass]="{'has-danger':!form.get('site_id').valid}"> 
     <label for="site_id" class="form-control-label">Site</label> 
     <input id="site_id" [formControl]="site_id_control" type="text" placeholder="Site" class="form-control input-sm"> 
     <div *ngIf="!form.get('site_id').valid"> 
      <div class="form-control-feedback">Site is required?</div> 
      <small class="form-text text-muted">Please enter a Site, eg. xyz.</small> 
     </div> 
    </div> 

Nhìn vào [formControl] = "site_id_control"

Sau đó, theo cách này, bạn có thể thêm hoặc loại bỏ các xác nhận từ đó kiểm soát cụ thể như này:

bên trong lớp học của bạn:

export class JobSearchEditComponent { 
    private site_id_control=this.form.controls['site_id']; 

    updateValidator(){ 
     let exisitingValidators = this.site_id_control.validators; 
     this.site_id_control.setValidators(Validators.compose([...existingValidators , exampleValidator])) 

     // you probably also need this : 
     this.site_id_control.updateValueAndValidity(); 

    } 
} 
+0

Tôi sẽ cố gắng đó và cho phép bạn biết làm thế nào nó đi –

+2

@DavidCruwys bất kỳ tiến bộ về vấn đề này? – fidev

-2

Thêm Validator tùy chỉnh trong angular2 Mẫu phản hồi:

this.yourForGroup = this.formBuilder.group({  
    'yourKey': ['',[Validators.required,this.yourFunctionName]]  
)} 

this.yourFunctionName(control: FormControl){  
    return your operations..  
} 
+0

Điều này không trả lời câu hỏi của tôi, và về bản chất là những gì tôi đang làm bây giờ. Tôi muốn sử dụng cấu hình formBuilder.group trong tệp cấu hình biểu mẫu của tôi. Và sau đó thêm một trình xác thực tùy chỉnh vào một trong các FormControls từ thành phần của tôi, cũng lưu trữ trình xác thực tùy chỉnh –

Các vấn đề liên quan