繁体   English   中英

Angular 中的 'missingFormException' 使用 Reactive forms?

[英]'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 之前呈现。

需要明确的是,我的表单实际上确实被填充了,但是我收到了这个让我非常恼火的错误。

由于您在paramMapgetCourseByIdsubscribe中同步初始化myForm FromGroup,因此组件模板将无法(在初始化时)识别myForm实例,即 null,然后在initReactiveForm方法中对其进行初始化。

我认为要解决此问题,您需要:

  • 添加*ngIf="myForm" ,以仅在初始化myForm后呈现form元素。
  • 或者直接在ngOnInit中初始化myForm ,然后一旦数据来自patchValue ,您就可以为它getCourseById

暂无
暂无

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

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