简体   繁体   English

Angular 中的 'missingFormException' 使用 Reactive forms?

[英]'missingFormException ' in Angular using Reactive forms?

I'm getting some weird behavior which I don't know how to deal with.我遇到了一些我不知道如何处理的奇怪行为。

I have a template which is one big form, but I'll show only single input filed where the errors is showing.我有一个模板,它是一个大表格,但我只会在显示错误的地方显示单个输入字段。

    <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>

Now, in .ts file I'm basically fetching DTO from a service and initializing FormControl with bunch of FormGroups.现在,在.ts文件中,我基本上是从服务中获取 DTO 并使用一堆 FormGroups 初始化 FormControl。 They all work correct and map on the template as expected.它们都按预期在模板上正常工作和 map。 But once I use service from backend I'm getting an error.但是一旦我从后端使用服务,我就会收到错误消息。

 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]],
    
        })
    
 }

Inside ngOnInit()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;
      }

    });
    
  }

The error I'm getting looks like this:我收到的错误如下所示:

    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)

Line course.component.html:9:59 points at the beginning of [value]="course['id'] in the template.线course.component.html:9:59指向模板中[value]="course['id']的开头。

If I don't use firebaseService and just hardcode a object, this.course = Builider(Course).id("1").build();如果我不使用firebaseService而只是硬编码 object, this.course = Builider(Course).id("1").build(); then, form populates and everything works and no error in console.然后,表单填充,一切正常,控制台中没有错误。

Here is the service:这是服务:

public getAllCourses() : Observable<Course[]>{
    return this.fireDb.list<Course>('courses').valueChanges();
   
}

I'm actually fetching all the courses from Firebase and in subscribe() I take the first Course.我实际上是从 Firebase 获取所有课程,并在subscribe()中学习第一门课程。 Everything is console.log -ed and I have values I want.一切都是console.log -ed,我有我想要的值。 But somehow the template renders before I get the object.但不知何故,模板在我获得 object 之前呈现。

Just to be clear, my form does in fact gets populated, but I'm getting this error which annoys me so much.需要明确的是,我的表单实际上确实被填充了,但是我收到了这个让我非常恼火的错误。

Since you're initializing the myForm FromGroup synchronously within the subscribe of the paramMap and getCourseById , then the component template won't be able (while the initialization) to recognize the myForm instance which is null before initializing it in the initReactiveForm method.由于您在paramMapgetCourseByIdsubscribe中同步初始化myForm FromGroup,因此组件模板将无法(在初始化时)识别myForm实例,即 null,然后在initReactiveForm方法中对其进行初始化。

I think to resolve this issue you either need to:我认为要解决此问题,您需要:

  • Add *ngIf="myForm" , to render the form element only after initializing the myForm .添加*ngIf="myForm" ,以仅在初始化myForm后呈现form元素。
  • OR initialize the myForm directly within the ngOnInit , then you can patchValue to it once the data comes from the getCourseById .或者直接在ngOnInit中初始化myForm ,然后一旦数据来自patchValue ,您就可以为它getCourseById

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM