[英]Angular 5 FormBuilder errors undefined when invalid input
[當新手嘗試將其放入plnkr時,但是不能; 將@ angular / forms添加到json時出現問題。]
目的:整理在FormBuilder HTML中完成所有工作所需的知識:
<input type="text"
formControlName="bucket"
value="A"
[(ngModel)]="AllData.bucket" />
// added to button to test: [disabled]="this.myTestForm.invalid || this.myTestForm.pristine"
<div><button
type="submit">submit</button></div>
</form>
<div *ngIf="result.length > 0 ">{{result}}</div>
<div *ngIf="myTestForm.errors === true ">ERRORS FOUND</div>
運行應用程序:在下面的ts中顯示formbuilder會正確初始化輸入字段,如果我在上面添加了注釋的[disabled]表達式,則會正確禁用按鈕。
這是ts:從'@ angular / core'導入{Component,OnInit}; 從“ @ angular / forms”導入{Validators,FormBuilder,FormGroup};
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
myTestForm: FormGroup;
result: string;
AllData = { //// wired to ngModel
bucket: '12'
}
constructor(private fb: FormBuilder) {
this.result = '';
}
ngOnInit() {
this.myTestForm = this.fb.group({
bucket: ['starting value', [Validators.required, Validators.minLength(5)]]
<-- ngModel bucket above overrides this init value as expected -->
});
}
onSubmit(value: any) { // ways to show results
this.result = this.AllData.bucket;
// OR //
this.result = this.myTestForm.controls['bucket'].value;
// OR //
this.result = this.myTestForm.get('bucket').value;
}
}
應用程序按預期在輸入字段中以“ 12”啟動。 無論我按提交按鈕之前在文本框中輸入了什么內容,devTools始終將myTestForm'error'屬性顯示為未定義。
我期望錯誤根據正在發生的錯誤的類型而具有某種字符串。
此外,我在網上搜索了如何在出現錯誤后立即捕獲無效字段(當然是!pristine字段)的方法,但是我什么也無法工作。
任何幫助都感激不盡。
預先感謝,查克
我創建了一個小演示 ,對您的方法提供了建議
使用反應式表單方法時,請勿使用[(ngModel)]
,因為ngModel
將優先於formControl
並將其值設置為該控件,而與已初始化的formcontrol's
值formcontrol's
。
<form [formGroup]="myTestForm" > <input type="text" formControlName="bucket" value="A" /> <div><button [disabled]="myTestForm.invalid || myTestForm.pristine" type="submit" >submit</button></div> </form>
要檢查表單錯誤,請在controls
上使用hasError()
<div *ngIf="myTestForm.get('bucket').hasError('required')">Input is required</div> <div *ngIf="myTestForm.get('bucket').hasError('minlength')">Min length should be 5</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.