[英]'missingFormException ' in Angular using Reactive forms?
我遇到了一些我不知道如何處理的奇怪行為。
我有一個模板,它是一個大表格,但我只會在顯示錯誤的地方顯示單個輸入字段。
<form [formGroup]="myForm" (ngSubmit)="submitForm()" class="row g-3 needs-validation" novalidate>
<div class="col-md-4">
<label for="idCourse" class="form-label">ID</label>
<input type="text" class="form-control" [value]="course['id']" disabled id="idCourse" >
</div>
</form>
現在,在.ts
文件中,我基本上是從服務中獲取 DTO 並使用一堆 FormGroups 初始化 FormControl。 它們都按預期在模板上正常工作和 map。 但是一旦我從后端使用服務,我就會收到錯誤消息。
initReactiveForm() {
this.myForm = this.fb.group({
// id:[this.course['id'], [ ]], since this input field is disabled I'm not adding it to form, but I tried adding it as well, didn't do the job
name:[this.course['name'], [Validators.required, Validators.minLength(3), Validator.cannotContainWhitespaceOnly]],
})
}
在ngOnInit()
內部
ngOnInit(): void {
this.activatedRoute.paramMap.subscribe(params => {
var courseId = params.get('courseIdPlaceholder');
//some custom validation and simple checks...
if (courseId) {
//check in service layer if Course exists for given Id; this won't work
this.firebaseService.getCourseById(courseId).subscribe(course => {
this.course = course ;
this.initReactiveForm();
});
//this.course = Builider(Course).id("1").build(); but this works if I comment out above code which fetches Course from service
// this.initReactiveForm();
} else {
alert("Not valid id!")
this.router.navigate(["/home"]);
return;
}
});
}
我收到的錯誤如下所示:
core.mjs:6485 ERROR Error: formGroup expects a FormGroup instance. Please pass one in.
Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
firstName: new FormControl()
});
at missingFormException (forms.mjs:1494:12)
at FormGroupDirective._checkFormPresent (forms.mjs:5523:19)
at FormGroupDirective.ngOnChanges (forms.mjs:5296:14)
at FormGroupDirective.rememberChangeHistoryAndInvokeOnChangesHook (core.mjs:1508:1)
at callHook (core.mjs:2552:1)
at callHooks (core.mjs:2511:1)
at executeInitAndCheckHooks (core.mjs:2462:1)
at selectIndexInternal (core.mjs:8405:1)
at Module.ɵɵadvance (core.mjs:8388:1)
at CourseComponent_Template (course.component.html:9:59)
線course.component.html:9:59
指向模板中[value]="course['id']
的開頭。
如果我不使用firebaseService
而只是硬編碼 object, this.course = Builider(Course).id("1").build();
然后,表單填充,一切正常,控制台中沒有錯誤。
這是服務:
public getAllCourses() : Observable<Course[]>{
return this.fireDb.list<Course>('courses').valueChanges();
}
我實際上是從 Firebase 獲取所有課程,並在subscribe()
中學習第一門課程。 一切都是console.log
-ed,我有我想要的值。 但不知何故,模板在我獲得 object 之前呈現。
需要明確的是,我的表單實際上確實被填充了,但是我收到了這個讓我非常惱火的錯誤。
由於您在paramMap
和getCourseById
的subscribe
中同步初始化myForm
FromGroup,因此組件模板將無法(在初始化時)識別myForm
實例,即 null,然后在initReactiveForm
方法中對其進行初始化。
我認為要解決此問題,您需要:
*ngIf="myForm"
,以僅在初始化myForm
后呈現form
元素。ngOnInit
中初始化myForm
,然后一旦數據來自patchValue
,您就可以為它getCourseById
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.