2016-07-16 61 views
0

我使用表單驗證器通過表單構建器在Angular 2中創建表單。表單驗證程序未通過Angular 2

每當我在文本框中輸入數據 - 它通過(div輪廓顏色變綠)。

當我用數據加載表單時,文本框有一個紅色的輪廓 - 即使它們被填充文本。

HTML:

<div class="form-group row" [ngClass]="{'has-error': (!firstname.valid), 'has-success': (firstname.valid)}"> 
     <label for="firstname" class="col-sm-2 control-label">First Name</label> 
     <div class="col-sm-10"> 
      <input [formControl]="firstname" type="text" class="form-control" id="firstname" placeholder="First Name" value="{{profile.firstname}}"> 
     </div> 
    </div> 

在組件文件:

@Input() profile: Profile; 

public form: FormGroup; 
public firstname: AbstractControl; 
public lastname: AbstractControl; 


    constructor(fb: FormBuilder) { 
    this.form = fb.group({ 
     'firstname': ['', Validators.compose([Validators.required, Validators.minLength(4)])], 
     'lastname': ['', Validators.compose([Validators.required, Validators.minLength(4)])], 
     'jobtitle': ['', Validators.compose([Validators.required, Validators.minLength(4)])], 
     'department': ['', Validators.compose([Validators.required, Validators.minLength(4)])] 
    }); 

    this.firstname = this.form.controls['firstname']; 
    this.lastname = this.form.controls['lastname']; 
    this.jobtitle = this.form.controls['jobtitle']; 
    this.department = this.form.controls['department']; 
} 

爲什麼驗證未通過,則Validators.required不正確的?

感謝。

+0

你的代碼似乎罰款,你能否pulnker重建問題了嗎? –

+0

將需要我一段時間才能得到。似乎「有錯誤」類設置爲早。 class =「form-group row has-error」 – thegunner

+0

因此,這意味着你得到你的解決方案? –

回答

1

我看到你正在使用模型驅動的形式,爲什麼不採用模型驅動的方式設定初始值:

'firstname': [profile.firstname, Validators.compose([Validators.required, Validators.minLength(4)])] 

如果你沒有在轉接過程中,初始化階段,真正的數據需要一些時間,使用後更新:

this.firstname.updateValue(this.profile.firstname); 

工作plnkr:http://plnkr.co/edit/UgsYOu04H0Y4kxGYwhAl?p=preview