使用模型和 formgroupdirective 时无法找到带有路径的控件

Unable to find control with path when using model and formgroupdirective

我的 Angular 8 应用程序使用了大量嵌套表单,为了尽量减少代码量,我建立了一个模型 class 来为我的反应式表单定义结构。我的 html 页面有一个嵌套组件的手风琴,它应该创建一个表单来添加或更新数据。当尝试使用基于模型结构的现有数据填充我的表单时,我现在收到一条错误消息(示例):错误错误:找不到路径为:'info -> charName'

的控件

在我的 home.ts 中,我导入导出的 classes 并像这样创建父表单:

this.CharGenMagusForm = this.fb.group({
  characterid: [''],
  playerUID: [''],
  covenantID: [''],
  info: this.fb.group(new Info()),
  infoMagus: this.fb.group(new InfoMagus),
  characteristics: this.fb.group(new Characteristics()),
  abilities: this.fb.group(new Abilities()),
  arts: this.fb.group(new Arts()),
  armour: this.fb.group(new Armour()),
  agingWarping: this.fb.group(new AgingWarping()),
  chargen: this.fb.group(new Chargen()),
  playerChar: ['']
})

在我的 home.html 中,我添加(示例)信息组件如下:

<mat-expansion-panel>
        <mat-expansion-panel-header>
          <mat-panel-title><h3>CHARACTER INFO</h3></mat-panel-title>
        </mat-expansion-panel-header>
        <ng-template matExpansionPanelContent>
          <hr />
          <form [formGroup]="CharGenMagusForm">
            <app-info [parent]="CharGenMagusForm" (CloseThisPanel)="onClose($event)"></app-info>
          </form>             
        </ng-template>
      </mat-expansion-panel>

info.ts中,我有以下内容:

  @Input() parent: FormGroup;
  @Output() CloseThisPanel = new EventEmitter<any>();

  infoData: Observable<Info>;
  fgd: FormGroupDirective;
  info: FormGroup;

constructor(private characterDetailsService: CharacterDetailsService, private fb: FormBuilder, parent: FormGroupDirective) {
    this.fgd = parent;
  }

  ngOnInit() {
    this.info = this.fgd.form;
    this.info.addControl('info', this.fb.group(new Info()));
    this.infoData = this.characterDetailsService.GetCharacterInfo().pipe(
      tap(infoData => this.parent.patchValue({info: infoData}))        <-------I suspect the problem lies here???
    );
  }

info.html 我有:

<div [formGroup] = "parent">
  <form *ngIf="infoData | async"  formGroupName="info">

<---and all the form control stuff--->

CharacterDetailsS​​ervice 使用 info.ts 的特定函数从 Firestore 获取所有数据,如:

GetCharacterInfo() {
  return of<Info>(this.characterInfoData);
}

信息模型class:

export class Info {
  public charName: string;
  public type: string;
  public covenant: string;
  public gender: string;
  public size: number;
  public bornYear: number;
  public currentYear: number;
  public charAge: number;
  public height: string;
  public weight: string;
  public hair: string;
  public eyes: string;
  public charPic: string;
  public charPicDataUrl: string;
}

对于我出错的地方,如果能提供一些帮助,我将不胜感激。

你的问题出在这一行:

info: this.fb.group(new Info())

在运行时这将等于:

info: this.fb.group({})

所以您基本上添加了一个没有嵌套控件的组(charName 不存在)。这是因为您的 class 没有为属性提供默认值,您可以通过将 class 更改为这样

来修复它
export class Info {
  public charName: string = '';
  public type: string  = '';
  public covenant: string  = '';
...