首页 > 解决方案 > 使用模型和表单组指令时无法找到带有路径的控件

问题描述

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

在我的home.ts中,我导入导出的类并创建父表单,如下所示:

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);
}

信息模型类:

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

我会感谢一些关于我哪里出错的帮助。

标签: angularangular-reactive-forms

解决方案


您的问题出在这一行:

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

在运行时,这将等于:

info: this.fb.group({})

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

export class Info {
  public charName: string = '';
  public type: string  = '';
  public covenant: string  = '';
...

推荐阅读