在 Angular 中,如何在同一组件内的单独 ng-template 中分离反应形式的部分?

问题描述 投票:0回答:1

我想使用来自 ng-template 的角反应形式的某些部分。分离在不同的组件中可以很好地使用 ngViewProviders。但我想通过 ng-template 来实现它。

        <h1>Test Reactive Form</h1>
        <form [formGroup]="form">
          <ng-container
          [ngTemplateOutlet]="formArray"
          [ngTemplateOutletContext]="{formGroup:form, arrayName:test}"
          ></ng-container>
        </form> 
        {{form.value | json}}

        <ng-template #formArray let-formGroup="formGroup" let-arrayName="arrayName"  >
          
          <ng-container [formGroup]="formGroup">
        <div formArray="arrayName">
            <ng-container *ngFor="let t of arrayName.controls;let i = index;" [formGroupName]="i">
              {{formGroup.value | json}}
            <input type="text"/>
            </ng-container>
          </div>
          </ng-container>
        </ng-template>
      `,
    })
    export class App {
      name = 'Angular';
      form;
      constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
          test: this.fb.array([]),
        });

        const test = this.fb.group({
          name: 'Test name',
        });
        this.test.push(test);
        const test_1 = this.fb.group({
          name: 'test name 2',
        });
        this.test.push(test_1);
      }

      get test(): FormArray {
        return this.form.get('test') as FormArray;
      }

出现类似错误 错误 错误:找不到名称为“0”的控件

Stackbitz 链接:https://stackblitz.com/edit/angular-9jmcfq?file=src%2Fmain.ts

angular angular-forms angular-template
1个回答
0
投票

属性

formGroupName
formGroup
formArray
formArrayName
必须定义正确的 HTML 元素。

之前:

<ng-container *ngFor="let t of arrayName.controls;let i = index;" 
    [formGroupName]="i">
      {{formGroup.value | json}}
      <input type="text"/>
</ng-container>

之后:

<div *ngFor="let t of arrayName.controls;let i = index;" 
    [formGroupName]="i">
      {{formGroup.value | json}}
      <input type="text"/>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.